blob: d008f26bead6b22f012307b771690dffb2b592ca [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;
Mathias Agopian99b49842011-06-27 16:05:52 -0700200
Kalle Raitaa099a242017-01-11 11:17:29 -0800201std::string getHwcServiceName() {
202 char value[PROPERTY_VALUE_MAX] = {};
203 property_get("debug.sf.hwc_service_name", value, "default");
204 ALOGI("Using HWComposer service: '%s'", value);
205 return std::string(value);
206}
207
208bool useTrebleTestingOverride() {
209 char value[PROPERTY_VALUE_MAX] = {};
210 property_get("debug.sf.treble_testing_override", value, "false");
211 ALOGI("Treble testing override: '%s'", value);
212 return std::string(value) == "true";
213}
214
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800215std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
216 switch(displayColorSetting) {
217 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800219 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700220 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800221 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700222 return std::string("Enhanced");
223 default:
224 return std::string("Unknown ") +
225 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800227}
228
Lloyd Pique99d3da52018-01-22 17:48:03 -0800229NativeWindowSurface::~NativeWindowSurface() = default;
230
231namespace impl {
232
233class NativeWindowSurface final : public android::NativeWindowSurface {
234public:
235 static std::unique_ptr<android::NativeWindowSurface> create(
236 const sp<IGraphicBufferProducer>& producer) {
237 return std::make_unique<NativeWindowSurface>(producer);
238 }
239
240 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
241 : surface(new Surface(producer, false)) {}
242
243 ~NativeWindowSurface() override = default;
244
245private:
246 sp<ANativeWindow> getNativeWindow() const override { return surface; }
247
248 void preallocateBuffers() override { surface->allocateBuffers(); }
249
250 sp<Surface> surface;
251};
252
253} // namespace impl
254
David Sodmanbc815282017-11-05 18:57:52 -0800255SurfaceFlingerBE::SurfaceFlingerBE()
256 : mHwcServiceName(getHwcServiceName()),
257 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800258 mFrameBuckets(),
259 mTotalTime(0),
260 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800261 mComposerSequenceId(0) {
262}
263
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800264SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800265 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700267 mTransactionPending(false),
268 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700269 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700270 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700271 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700273 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800275 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800276 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800277 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800278 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700279 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700280 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700281 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700282 mDebugInTransaction(0),
283 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700284 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700285 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700286 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800287 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800288 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800289 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700290 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800291 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800292 mCreateBufferQueue(&BufferQueue::createBufferQueue),
293 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800294
295SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800296 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800297
298 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
300
301 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
303
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800304 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
305 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800306
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700307 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
309
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700310 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
311 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
312
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800313 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
314 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
315
Steven Thomas050b2c82017-03-06 11:45:16 -0800316 // Vr flinger is only enabled on Daydream ready devices.
317 useVrFlinger = getBool< ISurfaceFlingerConfigs,
318 &ISurfaceFlingerConfigs::useVrFlinger>(false);
319
Fabien Sanglard1971b632017-03-10 14:50:03 -0800320 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
321 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
322
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600323 hasWideColorDisplay =
324 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700325 useColorManagement =
326 getBool<V1_2::ISurfaceFlingerConfigs, &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600327
Peiyong Linb3839ad2018-09-05 15:37:19 -0700328 useContextPriority = getBool<ISurfaceFlingerConfigs,
329 &ISurfaceFlingerConfigs::useContextPriority>(true);
330
Iris Chang7501ed62018-04-30 14:45:42 +0800331 V1_1::DisplayOrientation primaryDisplayOrientation =
332 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
333 V1_1::DisplayOrientation::ORIENTATION_0);
334
335 switch (primaryDisplayOrientation) {
336 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800347 break;
348 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700349 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800350
Lloyd Pique41be5d22018-06-21 13:11:48 -0700351 // Note: We create a local temporary with the real DispSync implementation
352 // type temporarily so we can initialize it with the configured values,
353 // before storing it for more generic use using the interface type.
354 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
355 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
356 SurfaceFlinger::dispSyncPresentTimeOffset);
357 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700358
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800359 // debugging stuff...
360 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361
Mathias Agopianb4b17302013-03-20 18:36:41 -0700362 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700363 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700364
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365 property_get("debug.sf.showupdates", value, "0");
366 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700367
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368 property_get("debug.sf.ddms", value, "0");
369 mDebugDDMS = atoi(value);
370 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700371 if (!startDdmConnection()) {
372 // start failed, and DDMS debugging not enabled
373 mDebugDDMS = 0;
374 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700375 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700376 ALOGI_IF(mDebugRegion, "showupdates enabled");
377 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700378
379 property_get("debug.sf.disable_backpressure", value, "0");
380 mPropagateBackpressure = !atoi(value);
381 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700382
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800383 property_get("debug.sf.enable_hwc_vds", value, "0");
384 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800385 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800386
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800387 property_get("ro.sf.disable_triple_buffer", value, "1");
388 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800389 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700390
Yiwei Zhang243b3782018-05-15 17:40:04 -0700391 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700392 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
393 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
394
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200395 property_get("debug.sf.early_phase_offset_ns", value, "-1");
396 const int earlySfOffsetNs = atoi(value);
397
398 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
399 const int earlyGlSfOffsetNs = atoi(value);
400
401 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
402 const int earlyAppOffsetNs = atoi(value);
403
404 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
405 const int earlyGlAppOffsetNs = atoi(value);
406
Ana Krulec98b5b242018-08-10 15:03:23 -0700407 property_get("debug.sf.use_scheduler", value, "0");
408 mUseScheduler = atoi(value);
409
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200410 const VSyncModulator::Offsets earlyOffsets =
411 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
412 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
413 const VSyncModulator::Offsets earlyGlOffsets =
414 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
415 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
416 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
417 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700418
Romain Guy11d63f42017-07-20 12:47:14 -0700419 // We should be reading 'persist.sys.sf.color_saturation' here
420 // but since /data may be encrypted, we need to wait until after vold
421 // comes online to attempt to read the property. The property is
422 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800423
424 if (useTrebleTestingOverride()) {
425 // Without the override SurfaceFlinger cannot connect to HIDL
426 // services that are not listed in the manifests. Considered
427 // deriving the setting from the set service name, but it
428 // would be brittle if the name that's not 'default' is used
429 // for production purposes later on.
430 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
431 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432}
433
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800434void SurfaceFlinger::onFirstRef()
435{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800436 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437}
438
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800439SurfaceFlinger::~SurfaceFlinger()
440{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800441}
442
Dan Stozac7014012014-02-14 15:03:43 -0800443void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444{
445 // the window manager died on us. prepare its eulogy.
446
Andy McFadden13a082e2012-08-24 10:16:42 -0700447 // restore initial conditions (default device unblank, etc)
448 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800449
450 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700451 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800452}
453
Robert Carr1db73f62016-12-21 12:58:51 -0800454static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700455 status_t err = client->initCheck();
456 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800457 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800458 }
Robert Carr1db73f62016-12-21 12:58:51 -0800459 return nullptr;
460}
461
462sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
463 return initClient(new Client(this));
464}
465
466sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
467 const sp<IGraphicBufferProducer>& gbp) {
468 if (authenticateSurfaceTexture(gbp) == false) {
469 return nullptr;
470 }
471 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
472 if (layer == nullptr) {
473 return nullptr;
474 }
475
476 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800477}
478
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700479sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
480 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700481{
482 class DisplayToken : public BBinder {
483 sp<SurfaceFlinger> flinger;
484 virtual ~DisplayToken() {
485 // no more references, this display must be terminated
486 Mutex::Autolock _l(flinger->mStateLock);
487 flinger->mCurrentState.displays.removeItem(this);
488 flinger->setTransactionFlags(eDisplayTransactionNeeded);
489 }
490 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700491 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700492 : flinger(flinger) {
493 }
494 };
495
496 sp<BBinder> token = new DisplayToken(this);
497
498 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700499 DisplayDeviceState info;
500 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700501 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700502 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800504 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505 return token;
506}
507
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700508void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700509 Mutex::Autolock _l(mStateLock);
510
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700511 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700512 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700513 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700514 return;
515 }
516
517 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700518 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 ALOGE("destroyDisplay called for non-virtual display");
520 return;
521 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700522 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700523 mCurrentState.displays.removeItemsAt(idx);
524 setTransactionFlags(eDisplayTransactionNeeded);
525}
526
Mathias Agopiane57f2922012-08-09 16:29:12 -0700527sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700528 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700529 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800530 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700531 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700532 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700533}
534
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535void SurfaceFlinger::bootFinished()
536{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700537 if (mStartPropertySetThread->join() != NO_ERROR) {
538 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800539 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540 const nsecs_t now = systemTime();
541 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000542 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543
544 // wait patiently for the window manager death
545 const String16 name("window");
546 sp<IBinder> window(defaultServiceManager()->getService(name));
547 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700548 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 }
550
Steven Thomas050b2c82017-03-06 11:45:16 -0800551 if (mVrFlinger) {
552 mVrFlinger->OnBootFinished();
553 }
554
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700556 // formerly we would just kill the process, but we now ask it to exit so it
557 // can choose where to stop the animation.
558 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700559
560 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
561 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
562 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700563
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800564 postMessageAsync(new LambdaMessage([this] {
565 readPersistentProperties();
566 mBootStage = BootStage::FINISHED;
567 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800568}
569
Dan Stoza436ccf32018-06-21 12:10:12 -0700570uint32_t SurfaceFlinger::getNewTexture() {
571 {
572 std::lock_guard lock(mTexturePoolMutex);
573 if (!mTexturePool.empty()) {
574 uint32_t name = mTexturePool.back();
575 mTexturePool.pop_back();
576 ATRACE_INT("TexturePoolSize", mTexturePool.size());
577 return name;
578 }
579
580 // The pool was too small, so increase it for the future
581 ++mTexturePoolSize;
582 }
583
584 // The pool was empty, so we need to get a new texture name directly using a
585 // blocking call to the main thread
586 uint32_t name = 0;
587 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
588 return name;
589}
590
Mathias Agopian3f844832013-08-07 21:24:32 -0700591void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700592 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700593}
594
Wei Wangf9b05ee2017-07-19 20:59:39 -0700595// Do not call property_set on main thread which will be blocked by init
596// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700597void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700598 ALOGI( "SurfaceFlinger's main thread ready to run. "
599 "Initializing graphics H/W...");
600
Thierry Strudel2924d012017-08-14 15:19:37 -0700601 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800604
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700606 if (mUseScheduler) {
607 mScheduler = std::make_unique<Scheduler>();
608 mAppConnectionHandle =
609 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
610 SurfaceFlinger::vsyncPhaseOffsetNs,
611 [this] { resyncWithRateLimit(); },
612 impl::EventThread::InterceptVSyncsCallback());
613 mSfConnectionHandle =
614 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
615 SurfaceFlinger::sfVsyncPhaseOffsetNs,
616 [this] { resyncWithRateLimit(); },
617 [this](nsecs_t timestamp) {
618 mInterceptor->saveVSyncEvent(timestamp);
619 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800620
Ana Krulec98b5b242018-08-10 15:03:23 -0700621 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
622 mVsyncModulator.setEventThreads(mScheduler->getEventThread(mSfConnectionHandle),
623 mScheduler->getEventThread(mAppConnectionHandle));
624 } else {
625 mEventThreadSource =
626 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
627 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
628 mEventThread =
629 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
630 [this] { resyncWithRateLimit(); },
631 impl::EventThread::InterceptVSyncsCallback(),
632 "appEventThread");
633 mSfEventThreadSource =
634 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
635 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
636
637 mSFEventThread =
638 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
639 [this] { resyncWithRateLimit(); },
640 [this](nsecs_t timestamp) {
641 mInterceptor->saveVSyncEvent(timestamp);
642 },
643 "sfEventThread");
644 mEventQueue->setEventThread(mSFEventThread.get());
645 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
646 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800647
Steven Thomasb02664d2017-07-26 18:48:28 -0700648 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700649 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700650 renderEngineFeature |= (useColorManagement ?
651 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700652 renderEngineFeature |= (useContextPriority ?
653 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin833074a2018-08-28 11:53:54 -0700654 getBE().mRenderEngine = renderengine::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
Peiyong Linb3839ad2018-09-05 15:37:19 -0700655 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800656 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700657
658 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
659 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800660 getBE().mHwc.reset(
661 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700662 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800663 // Process any initial hotplug and resulting display changes.
664 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700665 const auto display = getDefaultDisplayDeviceLocked();
666 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
667 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
668 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800669
Lloyd Piquefcd86612017-12-14 17:15:36 -0800670 // make the default display GLContext current so that we can create textures
671 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700672 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800673
Steven Thomas050b2c82017-03-06 11:45:16 -0800674 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700675 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700676 // This callback is called from the vr flinger dispatch thread. We
677 // need to call signalTransaction(), which requires holding
678 // mStateLock when we're not on the main thread. Acquiring
679 // mStateLock from the vr flinger dispatch thread might trigger a
680 // deadlock in surface flinger (see b/66916578), so post a message
681 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700682 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700683 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
684 mVrFlingerRequestsDisplay = requestDisplay;
685 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700686 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700688 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
689 getHwComposer()
690 .getHwcDisplayId(display->getId())
691 .value_or(0),
692 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800693 if (!mVrFlinger) {
694 ALOGE("Failed to start vrflinger");
695 }
696 }
697
Lloyd Pique379adc12018-01-22 17:31:47 -0800698 mEventControlThread = std::make_unique<impl::EventControlThread>(
699 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700700
Mathias Agopian92a979a2012-08-02 18:32:23 -0700701 // initialize our drawing state
702 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700703
Andy McFadden13a082e2012-08-24 10:16:42 -0700704 // set initial conditions (e.g. unblank default device)
705 initializeDisplays();
706
David Sodmanbc815282017-11-05 18:57:52 -0800707 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700708
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 // Inform native graphics APIs whether the present timestamp is supported:
710 if (getHwComposer().hasCapability(
711 HWC2::Capability::PresentFenceIsNotReliable)) {
712 mStartPropertySetThread = new StartPropertySetThread(false);
713 } else {
714 mStartPropertySetThread = new StartPropertySetThread(true);
715 }
716
717 if (mStartPropertySetThread->Start() != NO_ERROR) {
718 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800720
Chia-I Wud49d6692018-06-27 07:17:41 +0800721 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
722 // is used to saturate legacy sRGB content. However, to make sure the same color under
723 // Display P3 will be saturated to the same color, we intentionally break the API spec
724 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
725 // such saturation matrix on Display P3 is understood fully, the API should always return
726 // identify matrix.
727 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
728 Dataspace::SRGB_LINEAR);
729
730 // we will apply this on Display P3.
731 if (mEnhancedSaturationMatrix != mat4()) {
732 ColorSpace srgb(ColorSpace::sRGB());
733 ColorSpace displayP3(ColorSpace::DisplayP3());
734 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
735 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
736 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
737 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800738
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700740}
741
Romain Guy11d63f42017-07-20 12:47:14 -0700742void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700743 Mutex::Autolock _l(mStateLock);
744
Romain Guy11d63f42017-07-20 12:47:14 -0700745 char value[PROPERTY_VALUE_MAX];
746
747 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700749 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100751
752 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700753 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700754}
755
Mathias Agopiana67e4182012-06-19 17:26:12 -0700756void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800757 // Start boot animation service by setting a property mailbox
758 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800760 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 if (mStartPropertySetThread->join() != NO_ERROR) {
762 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800763 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764}
765
Mathias Agopian875d8e12013-06-07 15:35:48 -0700766size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800767 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700768}
769
Mathias Agopian875d8e12013-06-07 15:35:48 -0700770size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800771 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700772}
773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800774// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800775
Jamie Gennis582270d2011-08-17 18:19:00 -0700776bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800777 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800778 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800779 return authenticateSurfaceTextureLocked(bufferProducer);
780}
781
782bool SurfaceFlinger::authenticateSurfaceTextureLocked(
783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800784 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800785 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800786}
787
Brian Anderson6b376712017-04-04 10:51:39 -0700788status_t SurfaceFlinger::getSupportedFrameTimestamps(
789 std::vector<FrameEvent>* outSupported) const {
790 *outSupported = {
791 FrameEvent::REQUESTED_PRESENT,
792 FrameEvent::ACQUIRE,
793 FrameEvent::LATCH,
794 FrameEvent::FIRST_REFRESH_START,
795 FrameEvent::LAST_REFRESH_START,
796 FrameEvent::GPU_COMPOSITION_DONE,
797 FrameEvent::DEQUEUE_READY,
798 FrameEvent::RELEASE,
799 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700800 ConditionalLock _l(mStateLock,
801 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700802 if (!getHwComposer().hasCapability(
803 HWC2::Capability::PresentFenceIsNotReliable)) {
804 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
805 }
806 return NO_ERROR;
807}
808
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
810 Vector<DisplayInfo>* configs) {
811 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 return BAD_VALUE;
813 }
814
Jesse Hall692c7232012-11-08 15:41:56 -0800815 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700816 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
817 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700818 type = i;
819 break;
820 }
821 }
822
823 if (type < 0) {
824 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700825 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700826
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 // TODO: Not sure if display density should handled by SF any longer
828 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700831 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800832 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700833 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 }
835 return density;
836 }
837 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700838 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700840 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 return getDensityFromProperty("ro.sf.lcd_density"); }
842 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700845
Steven Thomas6d8110b2017-08-31 18:24:21 -0700846 ConditionalLock _l(mStateLock,
847 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 DisplayInfo info = DisplayInfo();
850
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851 float xdpi = hwConfig->getDpiX();
852 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700853
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700854 info.w = hwConfig->getWidth();
855 info.h = hwConfig->getHeight();
856 // Default display viewport to display width and height
857 info.viewportW = info.w;
858 info.viewportH = info.h;
859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 if (type == DisplayDevice::DISPLAY_PRIMARY) {
861 // The density of the device is provided by a build property
862 float density = Density::getBuildDensity() / 160.0f;
863 if (density == 0) {
864 // the build doesn't provide a density -- this is wrong!
865 // use xdpi instead
866 ALOGE("ro.sf.lcd_density must be defined as a build property");
867 density = xdpi / 160.0f;
868 }
869 if (Density::getEmuDensity()) {
870 // if "qemu.sf.lcd_density" is specified, it overrides everything
871 xdpi = ydpi = density = Density::getEmuDensity();
872 density /= 160.0f;
873 }
874 info.density = density;
875
876 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700877 const auto display = getDefaultDisplayDeviceLocked();
878 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700879
880 // This is for screenrecord
881 const Rect viewport = display->getViewport();
882 if (viewport.isValid()) {
883 info.viewportW = uint32_t(viewport.getWidth());
884 info.viewportH = uint32_t(viewport.getHeight());
885 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 } else {
887 // TODO: where should this value come from?
888 static const int TV_DENSITY = 213;
889 info.density = TV_DENSITY / 160.0f;
890 info.orientation = 0;
891 }
892
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 info.xdpi = xdpi;
894 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800895 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900896 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800897
Andy McFadden91b2ca82014-06-13 14:04:23 -0700898 // This is how far in advance a buffer must be queued for
899 // presentation at a given time. If you want a buffer to appear
900 // on the screen at time N, you must submit the buffer before
901 // (N - presentationDeadline).
902 //
903 // Normally it's one full refresh period (to give SF a chance to
904 // latch the buffer), but this can be reduced by configuring a
905 // DispSync offset. Any additional delays introduced by the hardware
906 // composer or panel must be accounted for here.
907 //
908 // We add an additional 1ms to allow for processing time and
909 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800910 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800911 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700912
913 // All non-virtual displays are currently considered secure.
914 info.secure = true;
915
Iris Chang7501ed62018-04-30 14:45:42 +0800916 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700917 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800918 std::swap(info.w, info.h);
919 }
920
Michael Wright28f24d02016-07-12 13:30:53 -0700921 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700922 }
923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 return NO_ERROR;
925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
928 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return BAD_VALUE;
930 }
931
932 // FIXME for now we always return stats for the primary display
933 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700934 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
935 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700936 return NO_ERROR;
937}
938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
940 const auto display = getDisplayDevice(displayToken);
941 if (!display) {
942 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800943 return BAD_VALUE;
944 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700945
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700946 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700947}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700948
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700949void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
950 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700951 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700952 return;
953 }
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700956 ALOGW("Trying to set config for virtual display");
957 return;
958 }
959
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700960 display->setActiveConfig(mode);
961 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700962}
963
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700965 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966 Vector<DisplayInfo> configs;
967 getDisplayConfigs(displayToken, &configs);
968 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
969 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
970 configs.size());
971 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700972 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700973 const auto display = getDisplayDevice(displayToken);
974 if (!display) {
975 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
976 displayToken.get());
977 } else if (display->isVirtual()) {
978 ALOGW("Attempt to set active config %d for virtual display", mode);
979 } else {
980 setActiveConfigInternal(display, mode);
981 }
982 }));
983
Mathias Agopian888c8222012-08-04 21:10:38 -0700984 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700985}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700986status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
987 Vector<ColorMode>* outColorModes) {
988 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700989 return BAD_VALUE;
990 }
991
Michael Wright28f24d02016-07-12 13:30:53 -0700992 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700993 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
994 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -0700995 type = i;
996 break;
997 }
998 }
999
1000 if (type < 0) {
1001 return type;
1002 }
1003
Peiyong Lina52f0292018-03-14 17:26:31 -07001004 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001005 {
1006 ConditionalLock _l(mStateLock,
1007 std::this_thread::get_id() != mMainThreadId);
1008 modes = getHwComposer().getColorModes(type);
1009 }
Michael Wright28f24d02016-07-12 13:30:53 -07001010 outColorModes->clear();
1011 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1012
1013 return NO_ERROR;
1014}
1015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1017 if (const auto display = getDisplayDevice(displayToken)) {
1018 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001019 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001020 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001021}
1022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001023void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1024 Dataspace dataSpace, RenderIntent renderIntent) {
1025 ColorMode currentMode = display->getActiveColorMode();
1026 Dataspace currentDataSpace = display->getCompositionDataSpace();
1027 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001028
Peiyong Lin38e9a562018-04-10 16:24:20 -07001029 if (mode == currentMode && dataSpace == currentDataSpace &&
1030 renderIntent == currentRenderIntent) {
1031 return;
1032 }
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 ALOGW("Trying to set config for virtual display");
1036 return;
1037 }
1038
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039 display->setActiveColorMode(mode);
1040 display->setCompositionDataSpace(dataSpace);
1041 display->setActiveRenderIntent(renderIntent);
1042 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001043
1044 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1046 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001047}
1048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001050 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051 Vector<ColorMode> modes;
1052 getDisplayColorModes(displayToken, &modes);
1053 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1054 if (mode < ColorMode::NATIVE || !exists) {
1055 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1056 decodeColorMode(mode).c_str(), mode, displayToken.get());
1057 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001058 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059 const auto display = getDisplayDevice(displayToken);
1060 if (!display) {
1061 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1062 decodeColorMode(mode).c_str(), mode, displayToken.get());
1063 } else if (display->isVirtual()) {
1064 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1065 decodeColorMode(mode).c_str(), mode);
1066 } else {
1067 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1068 RenderIntent::COLORIMETRIC);
1069 }
1070 }));
1071
Michael Wright28f24d02016-07-12 13:30:53 -07001072 return NO_ERROR;
1073}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001074
Svetoslavd85084b2014-03-20 10:28:31 -07001075status_t SurfaceFlinger::clearAnimationFrameStats() {
1076 Mutex::Autolock _l(mStateLock);
1077 mAnimFrameTracker.clearStats();
1078 return NO_ERROR;
1079}
1080
1081status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1082 Mutex::Autolock _l(mStateLock);
1083 mAnimFrameTracker.getStats(outStats);
1084 return NO_ERROR;
1085}
1086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1088 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001089 Mutex::Autolock _l(mStateLock);
1090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091 const auto display = getDisplayDeviceLocked(displayToken);
1092 if (!display) {
1093 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001094 return BAD_VALUE;
1095 }
1096
Peiyong Linfb069302018-04-25 14:34:31 -07001097 // At this point the DisplayDeivce should already be set up,
1098 // meaning the luminance information is already queried from
1099 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001100 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001101 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1102 capabilities.getDesiredMaxLuminance(),
1103 capabilities.getDesiredMaxAverageLuminance(),
1104 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001105
1106 return NO_ERROR;
1107}
1108
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001109status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001110 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001111 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001112
Chia-I Wu90f669f2017-10-05 14:24:41 -07001113 if (mInjectVSyncs == enable) {
1114 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001115 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001116
Ana Krulec98b5b242018-08-10 15:03:23 -07001117 // TODO(akrulec): Part of the Injector should be refactored, so that it
1118 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 if (enable) {
1120 ALOGV("VSync Injections enabled");
1121 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001122 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001123 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001124 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001125 impl::EventThread::InterceptVSyncsCallback(),
1126 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001128 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001129 } else {
1130 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001131 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001132 }
1133
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001134 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001135 }));
1136
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001137 return NO_ERROR;
1138}
1139
1140status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 Mutex::Autolock _l(mStateLock);
1142
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001143 if (!mInjectVSyncs) {
1144 ALOGE("VSync Injections not enabled");
1145 return BAD_VALUE;
1146 }
1147 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1148 ALOGV("Injecting VSync inside SurfaceFlinger");
1149 mVSyncInjector->onInjectSyncEvent(when);
1150 }
1151 return NO_ERROR;
1152}
1153
Lloyd Pique755e3192018-01-31 16:46:15 -08001154status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1155 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001156 // Try to acquire a lock for 1s, fail gracefully
1157 const status_t err = mStateLock.timedLock(s2ns(1));
1158 const bool locked = (err == NO_ERROR);
1159 if (!locked) {
1160 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1161 return TIMED_OUT;
1162 }
1163
1164 outLayers->clear();
1165 mCurrentState.traverseInZOrder([&](Layer* layer) {
1166 outLayers->push_back(layer->getLayerDebugInfo());
1167 });
1168
1169 mStateLock.unlock();
1170 return NO_ERROR;
1171}
1172
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001173// ----------------------------------------------------------------------------
1174
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001175sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1176 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001177 if (mUseScheduler) {
1178 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1179 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1180 } else {
1181 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1182 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001183 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001184 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1185 return mSFEventThread->createEventConnection();
1186 } else {
1187 return mEventThread->createEventConnection();
1188 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001189 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001190}
1191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001192// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001193
1194void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001195 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001196}
1197
1198void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001199 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001200}
1201
1202void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001203 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001204}
1205
1206void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001207 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001208 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001209}
1210
1211status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001212 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001213 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001214}
1215
1216status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001217 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219 if (res == NO_ERROR) {
1220 msg->wait();
1221 }
1222 return res;
1223}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001224
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001225void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001226 do {
1227 waitForEvent();
1228 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001229}
1230
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001231void SurfaceFlinger::enableHardwareVsync() {
1232 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001233 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001234 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001235 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001236 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001237 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001238}
1239
Jesse Hall948fe0c2013-10-14 12:56:09 -07001240void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241 Mutex::Autolock _l(mHWVsyncLock);
1242
Jesse Hall948fe0c2013-10-14 12:56:09 -07001243 if (makeAvailable) {
1244 mHWVsyncAvailable = true;
1245 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001246 // Hardware vsync is not currently available, so abort the resync
1247 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001248 return;
1249 }
1250
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001251 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1252 if (!getHwComposer().isConnected(displayId)) {
1253 return;
1254 }
1255
1256 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001257 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001258
Lloyd Pique41be5d22018-06-21 13:11:48 -07001259 mPrimaryDispSync->reset();
1260 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001261
1262 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001263 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001264 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001265 mPrimaryHWVsyncEnabled = true;
1266 }
1267}
1268
Jesse Hall948fe0c2013-10-14 12:56:09 -07001269void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001270 Mutex::Autolock _l(mHWVsyncLock);
1271 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001272 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001273 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001274 mPrimaryHWVsyncEnabled = false;
1275 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001276 if (makeUnavailable) {
1277 mHWVsyncAvailable = false;
1278 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279}
1280
Tim Murray4a4e4a22016-04-19 16:29:23 +00001281void SurfaceFlinger::resyncWithRateLimit() {
1282 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001283
1284 // No explicit locking is needed here since EventThread holds a lock while calling this method
1285 static nsecs_t sLastResyncAttempted = 0;
1286 const nsecs_t now = systemTime();
1287 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001288 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001289 }
Dan Stoza57164302017-05-08 14:03:54 -07001290 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001291}
1292
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001293void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1294 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001295 ATRACE_NAME("SF onVsync");
1296
Steven Thomas3cfac282017-02-06 12:29:30 -08001297 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001298 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001299 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001300 return;
1301 }
1302
1303 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001304 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001305 return;
1306 }
1307
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001308 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1309 // For now, we don't do anything with external display vsyncs.
1310 return;
1311 }
1312
Jamie Gennisd1700752013-10-14 12:22:52 -07001313 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001314
Jamie Gennisd1700752013-10-14 12:22:52 -07001315 { // Scope for the lock
1316 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001317 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001318 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001320 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001321
1322 if (needsHwVsync) {
1323 enableHardwareVsync();
1324 } else {
1325 disableHardwareVsync(false);
1326 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001327}
1328
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001329void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001330 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1331 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001332}
1333
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001334void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001335 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001336 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001337 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001338
Lloyd Piqueba04e622017-12-14 17:11:26 -08001339 // Ignore events that do not have the right sequenceId.
1340 if (sequenceId != getBE().mComposerSequenceId) {
1341 return;
1342 }
1343
Steven Thomasb02664d2017-07-26 18:48:28 -07001344 // Only lock if we're not on the main thread. This function is normally
1345 // called on a hwbinder thread, but for the primary display it's called on
1346 // the main thread with the state lock already held, so don't attempt to
1347 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001348 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001349
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001350 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001351
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001352 if (std::this_thread::get_id() == mMainThreadId) {
1353 // Process all pending hot plug events immediately if we are on the main thread.
1354 processDisplayHotplugEventsLocked();
1355 }
1356
Lloyd Piqueba04e622017-12-14 17:11:26 -08001357 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001358}
1359
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001360void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001361 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001362 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001365 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001366}
1367
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001369 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001371 getHwComposer().setVsyncEnabled(disp,
1372 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001373}
1374
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001375// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001376void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001377 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001378 // Clear the drawing state so that the logic inside of
1379 // handleTransactionLocked will fire. It will determine the delta between
1380 // mCurrentState and mDrawingState and re-apply all changes when we make the
1381 // transition.
1382 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001383 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001384 mDisplays.clear();
1385}
1386
Steven Thomas050b2c82017-03-06 11:45:16 -08001387void SurfaceFlinger::updateVrFlinger() {
1388 if (!mVrFlinger)
1389 return;
1390 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001391 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001392 return;
1393 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001394
David Sodman105b7dc2017-11-04 20:28:14 -07001395 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001396 ALOGE("Vr flinger is only supported for remote hardware composer"
1397 " service connections. Ignoring request to transition to vr"
1398 " flinger.");
1399 mVrFlingerRequestsDisplay = false;
1400 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001401 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001402
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001403 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001404
Steven Thomas0123ac62018-07-12 11:32:34 -07001405 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001406 LOG_ALWAYS_FATAL_IF(!display);
1407 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001408 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1409 // called below. Clear the reference now so we don't accidentally use it
1410 // later.
1411 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001412
Steven Thomasb02664d2017-07-26 18:48:28 -07001413 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001414 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001415 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001416
Steven Thomasb02664d2017-07-26 18:48:28 -07001417 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001418 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001419 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1420 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001421 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001422
David Sodman105b7dc2017-11-04 20:28:14 -07001423 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1424 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001425
1426 if (vrFlingerRequestsDisplay) {
1427 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001428 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
1430 mVisibleRegionsDirty = true;
1431 invalidateHwcGeometry();
1432
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001433 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001434 display = getDefaultDisplayDeviceLocked();
1435 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001436 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001439 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001440 const nsecs_t period = activeConfig->getVsyncPeriod();
1441 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001442
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001443 // The present fences returned from vr_hwc are not an accurate
1444 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001445 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1446 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001447
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 // Use phase of 0 since phase is not known.
1449 // Use latency of 0, which will snap to the ideal latency.
1450 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001451
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001452 resyncToHardwareVsync(false);
1453
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454 android_atomic_or(1, &mRepaintEverything);
1455 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001456}
1457
Mathias Agopian4fec8732012-06-29 14:12:52 -07001458void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001459 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001460 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001461 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001462 bool frameMissed = !mHadClientComposition &&
1463 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001464 (mPreviousPresentFence->getSignalTime() ==
1465 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001466 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001467 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001468 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001469 mTimeStats.incrementMissedFrames();
1470 if (mPropagateBackpressure) {
1471 signalLayerUpdate();
1472 break;
1473 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001474 }
Dan Stoza50182882016-07-08 12:02:20 -07001475
Steven Thomas050b2c82017-03-06 11:45:16 -08001476 // Now that we're going to make it to the handleMessageTransaction()
1477 // call below it's safe to call updateVrFlinger(), which will
1478 // potentially trigger a display handoff.
1479 updateVrFlinger();
1480
Dan Stoza6b9454d2014-11-07 16:00:59 -08001481 bool refreshNeeded = handleMessageTransaction();
1482 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001483 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001484 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001485 // Signal a refresh if a transaction modified the window state,
1486 // a new buffer was latched, or if HWC has requested a full
1487 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001488 signalRefresh();
1489 }
1490 break;
1491 }
1492 case MessageQueue::REFRESH: {
1493 handleMessageRefresh();
1494 break;
1495 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001496 }
1497}
1498
Dan Stoza6b9454d2014-11-07 16:00:59 -08001499bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001500 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001501 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001502 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001504 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001505 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001506}
1507
Mathias Agopian4fec8732012-06-29 14:12:52 -07001508void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001509 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001510
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001511 mRefreshPending = false;
1512
David Sodmanfa9b2af2017-12-24 13:28:59 -08001513 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
David Sodman2b406362017-12-15 13:33:47 -08001514 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001515 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001516 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001517
David Sodmanfa9b2af2017-12-24 13:28:59 -08001518 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001519 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001520 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001521 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1522 setUpHWComposer(compositionInfo);
1523 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001524 prepareFrame(display);
1525 doDebugFlashRegions(display, repaintEverything);
1526 doComposition(display, repaintEverything);
1527 }
1528
Adrian Roos1e1a1282017-11-01 19:05:31 +01001529 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001530 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001531
1532 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001533 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001534
Dan Stozabfbffeb2016-07-21 14:49:33 -07001535 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001536 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001537 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001538 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001539 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001540
Jorim Jaggi90535212018-05-23 23:44:06 +02001541 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001542
David Sodman7e4ae112018-02-09 15:02:28 -08001543 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001544 for (const auto& [token, display] : mDisplays) {
1545 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001546 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001547 compositionInfo.hwc.hwcLayer = nullptr;
1548 }
David Sodmanba340492018-08-05 21:51:33 -07001549 }
David Sodman7e4ae112018-02-09 15:02:28 -08001550
1551 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001552}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001553
David Sodmanfa9b2af2017-12-24 13:28:59 -08001554
1555bool SurfaceFlinger::handleMessageInvalidate() {
1556 ATRACE_CALL();
1557 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001558}
1559
David Sodman79bba0e2018-08-05 18:07:49 -07001560void SurfaceFlinger::calculateWorkingSet() {
1561 ATRACE_CALL();
1562 ALOGV(__FUNCTION__);
1563
David Sodman79bba0e2018-08-05 18:07:49 -07001564 // build the h/w work list
1565 if (CC_UNLIKELY(mGeometryInvalid)) {
1566 mGeometryInvalid = false;
1567 for (const auto& [token, display] : mDisplays) {
1568 const auto displayId = display->getId();
1569 if (displayId >= 0) {
1570 const Vector<sp<Layer>>& currentLayers(
1571 display->getVisibleLayersSortedByZ());
1572 for (size_t i = 0; i < currentLayers.size(); i++) {
1573 const auto& layer = currentLayers[i];
1574
1575 if (!layer->hasHwcLayer(displayId)) {
1576 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1577 layer->forceClientComposition(displayId);
1578 continue;
1579 }
1580 }
1581
1582 layer->setGeometry(display, i);
1583 if (mDebugDisableHWC || mDebugRegion) {
1584 layer->forceClientComposition(displayId);
1585 }
1586 }
1587 }
1588 }
1589 }
1590
1591 // Set the per-frame data
1592 for (const auto& [token, display] : mDisplays) {
1593 const auto displayId = display->getId();
1594 if (displayId < 0) {
1595 continue;
1596 }
1597
1598 if (mDrawingState.colorMatrixChanged) {
1599 display->setColorTransform(mDrawingState.colorMatrix);
1600 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1601 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1602 "display %d: %d", displayId, result);
1603 }
1604 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1605 if (layer->isHdrY410()) {
1606 layer->forceClientComposition(displayId);
1607 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1608 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1609 !display->hasHDR10Support()) {
1610 layer->forceClientComposition(displayId);
1611 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1612 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1613 !display->hasHLGSupport()) {
1614 layer->forceClientComposition(displayId);
1615 }
1616
1617 if (layer->getForceClientComposition(displayId)) {
1618 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1619 layer->setCompositionType(displayId, HWC2::Composition::Client);
1620 continue;
1621 }
1622
1623 layer->setPerFrameData(display);
1624 }
1625
Peiyong Lin13effd12018-07-24 17:01:47 -07001626 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001627 ColorMode colorMode;
1628 Dataspace dataSpace;
1629 RenderIntent renderIntent;
1630 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1631 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1632 }
1633 }
1634
1635 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001636
1637 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001638 const auto displayId = display->getId();
1639 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001640 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1641 auto displayId = display->getId();
1642 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1643 if (!layer->setHwcLayer(displayId)) {
1644 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1645 }
David Sodman15fb96e2018-01-07 10:23:24 -08001646 layer->getBE().compositionInfo.hwc.displayId = displayId;
1647 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001648 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1649 }
1650 }
David Sodman79bba0e2018-08-05 18:07:49 -07001651}
1652
David Sodmanfa9b2af2017-12-24 13:28:59 -08001653void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001654{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001655 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001656 // is debugging enabled
1657 if (CC_LIKELY(!mDebugRegion))
1658 return;
1659
David Sodmanfa9b2af2017-12-24 13:28:59 -08001660 if (display->isPoweredOn()) {
1661 // transform the dirty region into this screen's coordinate space
1662 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1663 if (!dirtyRegion.isEmpty()) {
1664 // redraw the whole screen
1665 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001666
David Sodmanfa9b2af2017-12-24 13:28:59 -08001667 // and draw the dirty region
1668 const int32_t height = display->getHeight();
1669 auto& engine(getRenderEngine());
1670 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001671
David Sodmanfa9b2af2017-12-24 13:28:59 -08001672 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001673 }
1674 }
1675
David Sodmanfa9b2af2017-12-24 13:28:59 -08001676 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001677
1678 if (mDebugRegion > 1) {
1679 usleep(mDebugRegion * 1000);
1680 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001681
David Sodmanfa9b2af2017-12-24 13:28:59 -08001682 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001683 status_t result = display->prepareFrame(
1684 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001685 ALOGE_IF(result != NO_ERROR,
1686 "prepareFrame for display %d failed:"
1687 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001688 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001689 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001690}
1691
Adrian Roos1e1a1282017-11-01 19:05:31 +01001692void SurfaceFlinger::doTracing(const char* where) {
1693 ATRACE_CALL();
1694 ATRACE_NAME(where);
1695 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001696 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001697 }
1698}
1699
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001700void SurfaceFlinger::logLayerStats() {
1701 ATRACE_CALL();
1702 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001703 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001704 if (display->isPrimary()) {
1705 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001706 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001707 }
1708 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001709
1710 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001711 }
1712}
1713
David Sodman2b406362017-12-15 13:33:47 -08001714void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001716 ATRACE_CALL();
1717 ALOGV("preComposition");
1718
David Sodman2b406362017-12-15 13:33:47 -08001719 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1720
Mathias Agopiancd60f992012-08-16 16:28:27 -07001721 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001722 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001723 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001724 needExtraInvalidate = true;
1725 }
Robert Carr2047fae2016-11-28 14:09:09 -08001726 });
1727
Mathias Agopiancd60f992012-08-16 16:28:27 -07001728 if (needExtraInvalidate) {
1729 signalLayerUpdate();
1730 }
1731}
1732
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001733void SurfaceFlinger::updateCompositorTiming(
1734 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1735 std::shared_ptr<FenceTime>& presentFenceTime) {
1736 // Update queue of past composite+present times and determine the
1737 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001738 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001739 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001740 while (!getBE().mCompositePresentTimes.empty()) {
1741 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001742 // Cached values should have been updated before calling this method,
1743 // which helps avoid duplicate syscalls.
1744 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1745 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1746 break;
1747 }
1748 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001749 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001750 }
1751
1752 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001753 while (getBE().mCompositePresentTimes.size() > 16) {
1754 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001755 }
1756
Brian Andersond0010582017-03-07 13:20:31 -08001757 setCompositorTimingSnapped(
1758 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1759}
1760
1761void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1762 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001763 // Integer division and modulo round toward 0 not -inf, so we need to
1764 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001765 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001766 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1767 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1768
Brian Andersond0010582017-03-07 13:20:31 -08001769 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1770 if (idealLatency <= 0) {
1771 idealLatency = vsyncInterval;
1772 }
1773
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001774 // Snap the latency to a value that removes scheduling jitter from the
1775 // composition and present times, which often have >1ms of jitter.
1776 // Reducing jitter is important if an app attempts to extrapolate
1777 // something (such as user input) to an accurate diasplay time.
1778 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1779 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001780 nsecs_t bias = vsyncInterval / 2;
1781 int64_t extraVsyncs =
1782 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1783 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1784 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001785
David Sodman99974d22017-11-28 12:04:33 -08001786 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1787 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1788 getBE().mCompositorTiming.interval = vsyncInterval;
1789 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790}
1791
David Sodman2b406362017-12-15 13:33:47 -08001792void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001793{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001794 ATRACE_CALL();
1795 ALOGV("postComposition");
1796
Brian Anderson3546a3f2016-07-14 11:51:14 -07001797 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001798 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001799 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001800 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001801 }
1802
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001803 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001804 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001805
David Sodman73beded2017-11-15 11:56:06 -08001806 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001807 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001808 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001809 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001810 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001811 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001812 } else {
1813 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1814 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001815
David Sodman73beded2017-11-15 11:56:06 -08001816 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001817 mPreviousPresentFence =
1818 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1819 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001820 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001821
Lloyd Pique41be5d22018-06-21 13:11:48 -07001822 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1823 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001824
David Sodman2b406362017-12-15 13:33:47 -08001825 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001826 // when we started doing work for this frame, but that should be okay
1827 // since updateCompositorTiming has snapping logic.
1828 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001829 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001830 CompositorTiming compositorTiming;
1831 {
David Sodman99974d22017-11-28 12:04:33 -08001832 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1833 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001834 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001835
Robert Carr2047fae2016-11-28 14:09:09 -08001836 mDrawingState.traverseInZOrder([&](Layer* layer) {
1837 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001838 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001839 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001840 recordBufferingStats(layer->getName().string(),
1841 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001842 }
Robert Carr2047fae2016-11-28 14:09:09 -08001843 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001844
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001845 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001846 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001847 enableHardwareVsync();
1848 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001849 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001850 }
1851 }
1852
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001853 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001854 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001855 enableHardwareVsync();
1856 }
1857 }
1858
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001859 if (mAnimCompositionPending) {
1860 mAnimCompositionPending = false;
1861
Brian Anderson4e606e32017-03-16 15:34:57 -07001862 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001863 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001864 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001865 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001866 // The HWC doesn't support present fences, so use the refresh
1867 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001868 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001869 mAnimFrameTracker.setActualPresentTime(presentTime);
1870 }
1871 mAnimFrameTracker.advanceFrame();
1872 }
Dan Stozab90cf072015-03-05 11:05:59 -08001873
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001874 mTimeStats.incrementTotalFrames();
1875 if (mHadClientComposition) {
1876 mTimeStats.incrementClientCompositionFrames();
1877 }
1878
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001879 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001880 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001881 return;
1882 }
1883
1884 nsecs_t currentTime = systemTime();
1885 if (mHasPoweredOff) {
1886 mHasPoweredOff = false;
1887 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001888 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001889 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001890 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1891 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001892 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001893 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001894 }
David Sodman4a36e932017-11-07 14:29:47 -08001895 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001896 }
David Sodman4a36e932017-11-07 14:29:47 -08001897 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001898
1899 {
1900 std::lock_guard lock(mTexturePoolMutex);
1901 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1902 if (refillCount > 0) {
1903 const size_t offset = mTexturePool.size();
1904 mTexturePool.resize(mTexturePoolSize);
1905 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1906 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1907 }
1908 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001909}
1910
1911void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001912 ATRACE_CALL();
1913 ALOGV("rebuildLayerStacks");
1914
Mathias Agopiancd60f992012-08-16 16:28:27 -07001915 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001916 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001917 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001918 mVisibleRegionsDirty = false;
1919 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001920
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001921 for (const auto& pair : mDisplays) {
1922 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001923 Region opaqueRegion;
1924 Region dirtyRegion;
1925 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001926 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001927 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001928 const Rect bounds = display->getBounds();
1929 if (display->isPoweredOn()) {
1930 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001931
Jeff Sharkey76488112017-02-27 14:15:18 -07001932 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001933 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001934 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001935 Region drawRegion(tr.transform(
1936 layer->visibleNonTransparentRegion));
1937 drawRegion.andSelf(bounds);
1938 if (!drawRegion.isEmpty()) {
1939 layersSortedByZ.add(layer);
1940 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001941 // Clear out the HWC layer if this layer was
1942 // previously visible, but no longer is
1943 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001944 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001945 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001946 // WM changes display->layerStack upon sleep/awake.
1947 // Here we make sure we delete the HWC layers even if
1948 // WM changed their layer stack.
1949 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001950 }
1951
1952 // If a layer is not going to get a release fence because
1953 // it is invisible, but it is also going to release its
1954 // old buffer, add it to the list of layers needing
1955 // fences.
1956 if (hwcLayerDestroyed) {
1957 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1958 mLayersWithQueuedFrames.cend(), layer);
1959 if (found != mLayersWithQueuedFrames.cend()) {
1960 layersNeedingFences.add(layer);
1961 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001962 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001963 });
1964 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001965 display->setVisibleLayersSortedByZ(layersSortedByZ);
1966 display->setLayersNeedingFences(layersNeedingFences);
1967 display->undefinedRegion.set(bounds);
1968 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1969 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001970 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001971 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001972}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001973
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001974// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001975// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001976// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001977// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001978// The returned HDR data space is one of
1979// - Dataspace::UNKNOWN
1980// - Dataspace::BT2020_HLG
1981// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001982Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1983 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001984 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001985 *outHdrDataSpace = Dataspace::UNKNOWN;
1986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001987 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001988 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001989 case Dataspace::V0_SCRGB:
1990 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001991 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001992 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001993 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001994 case Dataspace::BT2020_PQ:
1995 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001996 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001997 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001998 case Dataspace::BT2020_HLG:
1999 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002000 // When there's mixed PQ content and HLG content, we set the HDR
2001 // data space to be BT2020_PQ and convert HLG to PQ.
2002 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2003 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002004 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002005 break;
2006 default:
2007 break;
2008 }
Romain Guy54f154a2017-10-24 21:40:32 +01002009 }
2010
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002011 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002012}
2013
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002014// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002015void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2016 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002017 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2018 *outMode = ColorMode::NATIVE;
2019 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002020 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002021 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002022 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002023
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002024 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026
Peiyong Lindfde5112018-06-05 10:58:41 -07002027 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002028 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002029 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002030 if (isHdr) {
2031 bestDataSpace = hdrDataSpace;
2032 }
2033
Chia-I Wu0d711262018-05-21 15:19:35 -07002034 RenderIntent intent;
2035 switch (mDisplayColorSetting) {
2036 case DisplayColorSetting::MANAGED:
2037 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002038 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002039 break;
2040 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002041 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002042 break;
2043 default: // vendor display color setting
2044 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2045 break;
2046 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002049}
2050
David Sodman10a41ff2018-08-05 12:14:17 -07002051void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2052{
2053 HWC2::Error error;
2054 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2055 "CompositionType is sideband, but sideband stream is nullptr");
2056 error = (compositionInfo.hwc.hwcLayer)
2057 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2058 if (error != HWC2::Error::None) {
2059 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2060 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2061 static_cast<int32_t>(error));
2062 }
2063}
2064
2065void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2066{
2067 HWC2::Error error;
2068
2069 if (!compositionInfo.hwc.skipGeometry) {
2070 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2071 ALOGE_IF(error != HWC2::Error::None,
2072 "[SF] Failed to set blend mode %s:"
2073 " %s (%d)",
2074 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2075 static_cast<int32_t>(error));
2076
2077 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2078 ALOGE_IF(error != HWC2::Error::None,
2079 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2080 compositionInfo.hwc.displayFrame.left,
2081 compositionInfo.hwc.displayFrame.right,
2082 compositionInfo.hwc.displayFrame.top,
2083 compositionInfo.hwc.displayFrame.bottom,
2084 to_string(error).c_str(), static_cast<int32_t>(error));
2085
2086 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2087 ALOGE_IF(error != HWC2::Error::None,
2088 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2089 compositionInfo.hwc.sourceCrop.left,
2090 compositionInfo.hwc.sourceCrop.right,
2091 compositionInfo.hwc.sourceCrop.top,
2092 compositionInfo.hwc.sourceCrop.bottom,
2093 to_string(error).c_str(), static_cast<int32_t>(error));
2094
2095 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2096 ALOGE_IF(error != HWC2::Error::None,
2097 "[SF] Failed to set plane alpha %.3f: "
2098 "%s (%d)",
2099 compositionInfo.hwc.alpha,
2100 to_string(error).c_str(), static_cast<int32_t>(error));
2101
2102
2103 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2104 ALOGE_IF(error != HWC2::Error::None,
2105 "[SF] Failed to set Z %u: %s (%d)",
2106 compositionInfo.hwc.z,
2107 to_string(error).c_str(), static_cast<int32_t>(error));
2108
2109 error = (compositionInfo.hwc.hwcLayer)
2110 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2111 ALOGE_IF(error != HWC2::Error::None,
2112 "[SF] Failed to set info (%d)",
2113 static_cast<int32_t>(error));
2114
2115 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2116 ALOGE_IF(error != HWC2::Error::None,
2117 "[SF] Failed to set transform %s: "
2118 "%s (%d)",
2119 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2120 static_cast<int32_t>(error));
2121 }
2122
2123 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2124 ALOGE_IF(error != HWC2::Error::None,
2125 "[SF] Failed to set composition type: %s (%d)",
2126 to_string(error).c_str(), static_cast<int32_t>(error));
2127
2128 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2129 ALOGE_IF(error != HWC2::Error::None,
2130 "[SF] Failed to set dataspace: %s (%d)",
2131 to_string(error).c_str(), static_cast<int32_t>(error));
2132
2133 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2134 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2135 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2136 "[SF] Failed to set hdrMetadata: %s (%d)",
2137 to_string(error).c_str(), static_cast<int32_t>(error));
2138
2139 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2140 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2141 ALOGE_IF(error != HWC2::Error::None,
2142 "[SF] Failed to set color: %s (%d)",
2143 to_string(error).c_str(), static_cast<int32_t>(error));
2144 }
2145
2146 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2147 ALOGE_IF(error != HWC2::Error::None,
2148 "[SF] Failed to set visible region: %s (%d)",
2149 to_string(error).c_str(), static_cast<int32_t>(error));
2150
2151 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2152 ALOGE_IF(error != HWC2::Error::None,
2153 "[SF] Failed to set surface damage: %s (%d)",
2154 to_string(error).c_str(), static_cast<int32_t>(error));
2155}
2156
2157void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2158{
2159 HWC2::Error error;
2160
2161 if (compositionInfo.hwc.fence) {
2162 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2163 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2164 ALOGE_IF(error != HWC2::Error::None,
2165 "[SF] Failed to set buffer: %s (%d)",
2166 to_string(error).c_str(), static_cast<int32_t>(error));
2167 }
2168}
2169
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002171{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002172 bool dirty = !display->getDirtyRegion(false).isEmpty();
2173 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2174 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002175
David Sodmanfa9b2af2017-12-24 13:28:59 -08002176 // If nothing has changed (!dirty), don't recompose.
2177 // If something changed, but we don't currently have any visible layers,
2178 // and didn't when we last did a composition, then skip it this time.
2179 // The second rule does two things:
2180 // - When all layers are removed from a display, we'll emit one black
2181 // frame, then nothing more until we get new layers.
2182 // - When a display is created with a private layer stack, we won't
2183 // emit any black frames until a layer is added to the layer stack.
2184 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002185
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002186 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2187 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002188 mustRecompose ? "doing" : "skipping",
2189 dirty ? "+" : "-",
2190 empty ? "+" : "-",
2191 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002192
David Sodmanfa9b2af2017-12-24 13:28:59 -08002193 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002194
David Sodmanfa9b2af2017-12-24 13:28:59 -08002195 if (mustRecompose) {
2196 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002197 }
2198}
2199
David Sodmanfa9b2af2017-12-24 13:28:59 -08002200void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002201{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002202 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203 if (!display->isPoweredOn()) {
2204 return;
David Sodman2b406362017-12-15 13:33:47 -08002205 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002206
David Sodmanfb95bcc2017-12-22 15:45:30 -08002207 status_t result = display->prepareFrame(
2208 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002209 ALOGE_IF(result != NO_ERROR,
2210 "prepareFrame for display %d failed:"
2211 " %d (%s)",
2212 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002213}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002214
David Sodman10a41ff2018-08-05 12:14:17 -07002215void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2216 ATRACE_CALL();
2217 ALOGV("setUpHWComposer");
2218
2219 switch (compositionInfo.compositionType)
2220 {
2221 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002222 break;
2223
David Sodman10a41ff2018-08-05 12:14:17 -07002224 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002225 if (compositionInfo.hwc.hwcLayer) {
2226 auto error = (compositionInfo.hwc.hwcLayer)->
2227 setCompositionType(compositionInfo.compositionType);
2228 ALOGE_IF(error != HWC2::Error::None,
2229 "[SF] Failed to set composition type: %s (%d)",
2230 to_string(error).c_str(), static_cast<int32_t>(error));
2231 }
David Sodman10a41ff2018-08-05 12:14:17 -07002232 break;
2233
2234 case HWC2::Composition::Sideband:
2235 configureHwcCommonData(compositionInfo);
2236 configureSidebandComposition(compositionInfo);
2237 break;
2238
2239 case HWC2::Composition::SolidColor:
2240 configureHwcCommonData(compositionInfo);
2241 break;
2242
2243 case HWC2::Composition::Device:
2244 case HWC2::Composition::Cursor:
2245 configureHwcCommonData(compositionInfo);
2246 configureDeviceComposition(compositionInfo);
2247 break;
2248 }
2249}
2250
David Sodmanfa9b2af2017-12-24 13:28:59 -08002251void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002252 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002253 ALOGV("doComposition");
2254
David Sodmanfa9b2af2017-12-24 13:28:59 -08002255 if (display->isPoweredOn()) {
2256 // transform the dirty region into this screen's coordinate space
2257 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002258
David Sodmanfa9b2af2017-12-24 13:28:59 -08002259 // repaint the framebuffer (if needed)
2260 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002261
David Sodmanfa9b2af2017-12-24 13:28:59 -08002262 display->dirtyRegion.clear();
2263 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002264 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002265 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002266}
2267
David Sodmanfa9b2af2017-12-24 13:28:59 -08002268void SurfaceFlinger::postFrame()
2269{
2270 // |mStateLock| not needed as we are on the main thread
2271 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2272 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2273 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2274 logFrameStats();
2275 }
2276 }
2277}
2278
2279void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002280{
Mathias Agopian841cde52012-03-01 15:44:37 -08002281 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002282 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002283
David Sodmanfa9b2af2017-12-24 13:28:59 -08002284 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002285
David Sodmanfa9b2af2017-12-24 13:28:59 -08002286 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002287 const auto displayId = display->getId();
2288 if (displayId >= 0) {
2289 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002290 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 display->onSwapBuffersCompleted();
2292 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002293 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002294 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002295 // The layer buffer from the previous frame (if any) is released
2296 // by HWC only when the release fence from this frame (if any) is
2297 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002298 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2299 if ((displayId >= 0) && hwcLayer) {
2300 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002301 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002302
2303 // If the layer was client composited in the previous frame, we
2304 // need to merge with the previous client target acquire fence.
2305 // Since we do not track that, always merge with the current
2306 // client target acquire fence when it is available, even though
2307 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002308 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002309 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002310 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002311 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002312
David Sodman10a41ff2018-08-05 12:14:17 -07002313 if (compositionInfo.layer) {
2314 compositionInfo.layer->onLayerDisplayed(releaseFence);
2315 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002316 }
Chia-I Wu83806892017-11-16 10:50:20 -08002317
2318 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002320 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002321 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002322 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002323 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002324 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002325 }
2326 }
2327
Dominik Laskowski7e045462018-05-30 13:02:02 -07002328 if (displayId >= 0) {
2329 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002330 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002331 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002332}
2333
Mathias Agopian87baae12012-07-31 12:38:26 -07002334void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335{
Mathias Agopian841cde52012-03-01 15:44:37 -08002336 ATRACE_CALL();
2337
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002338 // here we keep a copy of the drawing state (that is the state that's
2339 // going to be overwritten by handleTransactionLocked()) outside of
2340 // mStateLock so that the side-effects of the State assignment
2341 // don't happen with mStateLock held (which can cause deadlocks).
2342 State drawingState(mDrawingState);
2343
Mathias Agopianca4d3602011-05-19 15:38:14 -07002344 Mutex::Autolock _l(mStateLock);
2345 const nsecs_t now = systemTime();
2346 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347
Mathias Agopianca4d3602011-05-19 15:38:14 -07002348 // Here we're guaranteed that some transaction flags are set
2349 // so we can call handleTransactionLocked() unconditionally.
2350 // We call getTransactionFlags(), which will also clear the flags,
2351 // with mStateLock held to guarantee that mCurrentState won't change
2352 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002353
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002354 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002355 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002356 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002357
Mathias Agopianca4d3602011-05-19 15:38:14 -07002358 mLastTransactionTime = systemTime() - now;
2359 mDebugInTransaction = 0;
2360 invalidateHwcGeometry();
2361 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002362}
2363
Dominik Laskowski7e045462018-05-30 13:02:02 -07002364DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002365 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002366 // Figure out whether the event is for the primary display or an
2367 // external display by matching the Hwc display id against one for a
2368 // connected display. If we did not find a match, we then check what
2369 // displays are not already connected to determine the type. If we don't
2370 // have a connected primary display, we assume the new display is meant to
2371 // be the primary display, and then if we don't have an external display,
2372 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002373 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2374 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002375 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002376 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002377 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002378 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002379 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002380 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002381 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002382 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002383 return DisplayDevice::DISPLAY_EXTERNAL;
2384 }
2385
2386 return DisplayDevice::DISPLAY_ID_INVALID;
2387}
2388
Lloyd Piqueba04e622017-12-14 17:11:26 -08002389void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2390 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002391 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002392 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002393 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002394 continue;
2395 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002396
2397 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2398 ALOGE("External displays are not supported by the vr hardware composer.");
2399 continue;
2400 }
2401
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002402 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002403 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002404 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002405 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002406 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002407
2408 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002409 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002410 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002411 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002412 DisplayDeviceState info;
2413 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002414 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2415 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002416 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002417 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002418 mInterceptor->saveDisplayCreation(info);
2419 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002420 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002421 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002422
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002423 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002424 if (idx >= 0) {
2425 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002426 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002427 mCurrentState.displays.removeItemsAt(idx);
2428 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002429 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002430 }
2431
2432 processDisplayChangesLocked();
2433 }
2434
2435 mPendingHotplugEvents.clear();
2436}
2437
Lloyd Pique99d3da52018-01-22 17:48:03 -08002438sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002439 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002440 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002441 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002442 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002443 HdrCapabilities hdrCapabilities;
2444 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002445
Peiyong Lin13effd12018-07-24 17:01:47 -07002446 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002447 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002448 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002449 if (isWideColorMode(colorMode)) {
2450 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002451 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002452
Dominik Laskowski7e045462018-05-30 13:02:02 -07002453 std::vector<RenderIntent> renderIntents =
2454 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002455 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002456 }
tangrobin6753a022018-08-10 10:58:54 +08002457 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002458
tangrobin6753a022018-08-10 10:58:54 +08002459 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002460 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2461 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2462 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463
2464 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2465 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2466
2467 /*
2468 * Create our display's surface
2469 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002470 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002471 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002472 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002473 renderSurface->setNativeWindow(nativeWindow.get());
2474 const int displayWidth = renderSurface->queryWidth();
2475 const int displayHeight = renderSurface->queryHeight();
2476
2477 // Make sure that composition can never be stalled by a virtual display
2478 // consumer that isn't processing buffers fast enough. We have to do this
2479 // in two places:
2480 // * Here, in case the display is composed entirely by HWC.
2481 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2482 // window's swap interval in eglMakeCurrent, so they'll override the
2483 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002484 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2486 }
2487
Chia-I Wua02871c2018-08-27 14:38:23 -07002488 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2489 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2490
Lloyd Pique99d3da52018-01-22 17:48:03 -08002491 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002492 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002493
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002494 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002495 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2496 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002497 displayHeight, displayInstallOrientation, hasWideColorGamut,
2498 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2499 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500
2501 if (maxFrameBufferAcquiredBuffers >= 3) {
2502 nativeWindowSurface->preallocateBuffers();
2503 }
2504
2505 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002506 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2507 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002508 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002509 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002511 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002512 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002513 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002514 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002515 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002516 display->setLayerStack(state.layerStack);
2517 display->setProjection(state.orientation, state.viewport, state.frame);
2518 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002520 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002521}
2522
Lloyd Pique347200f2017-12-14 17:00:15 -08002523void SurfaceFlinger::processDisplayChangesLocked() {
2524 // here we take advantage of Vector's copy-on-write semantics to
2525 // improve performance by skipping the transaction entirely when
2526 // know that the lists are identical
2527 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2528 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2529 if (!curr.isIdenticalTo(draw)) {
2530 mVisibleRegionsDirty = true;
2531 const size_t cc = curr.size();
2532 size_t dc = draw.size();
2533
2534 // find the displays that were removed
2535 // (ie: in drawing state but not in current state)
2536 // also handle displays that changed
2537 // (ie: displays that are in both lists)
2538 for (size_t i = 0; i < dc;) {
2539 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2540 if (j < 0) {
2541 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002542 // Call makeCurrent() on the primary display so we can
2543 // be sure that nothing associated with this display
2544 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002545 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2546 defaultDisplay->makeCurrent();
2547 }
2548 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2549 display->disconnect(getHwComposer());
2550 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002551 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002552 if (mUseScheduler) {
2553 mScheduler->hotplugReceived(mAppConnectionHandle,
2554 EventThread::DisplayType::Primary, false);
2555 } else {
2556 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2557 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002558 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002559 if (mUseScheduler) {
2560 mScheduler->hotplugReceived(mAppConnectionHandle,
2561 EventThread::DisplayType::External, false);
2562 } else {
2563 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2564 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002565 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002566 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 } else {
2568 // this display is in both lists. see if something changed.
2569 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002570 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002571 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2572 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2573 if (state_binder != draw_binder) {
2574 // changing the surface is like destroying and
2575 // recreating the DisplayDevice, so we just remove it
2576 // from the drawing state, so that it get re-added
2577 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002578 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2579 display->disconnect(getHwComposer());
2580 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002581 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002582 mDrawingState.displays.removeItemsAt(i);
2583 dc--;
2584 // at this point we must loop to the next item
2585 continue;
2586 }
2587
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002588 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002589 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002590 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002591 }
2592 if ((state.orientation != draw[i].orientation) ||
2593 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002594 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002595 }
2596 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002597 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002598 }
2599 }
2600 }
2601 ++i;
2602 }
2603
2604 // find displays that were added
2605 // (ie: in current state but not in drawing state)
2606 for (size_t i = 0; i < cc; i++) {
2607 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2608 const DisplayDeviceState& state(curr[i]);
2609
2610 sp<DisplaySurface> dispSurface;
2611 sp<IGraphicBufferProducer> producer;
2612 sp<IGraphicBufferProducer> bqProducer;
2613 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002614 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002615
Dominik Laskowski7e045462018-05-30 13:02:02 -07002616 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002617 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002618 // Virtual displays without a surface are dormant:
2619 // they have external state (layer stack, projection,
2620 // etc.) but no internal state (i.e. a DisplayDevice).
2621 if (state.surface != nullptr) {
2622 // Allow VR composer to use virtual displays.
2623 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2624 int width = 0;
2625 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2626 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2627 int height = 0;
2628 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2629 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2630 int intFormat = 0;
2631 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2632 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002633 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002634
Dominik Laskowski7e045462018-05-30 13:02:02 -07002635 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2636 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002637 }
2638
2639 // TODO: Plumb requested format back up to consumer
2640
2641 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002642 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002643 bqProducer, bqConsumer,
2644 state.displayName);
2645
2646 dispSurface = vds;
2647 producer = vds;
2648 }
2649 } else {
2650 ALOGE_IF(state.surface != nullptr,
2651 "adding a supported display, but rendering "
2652 "surface is provided (%p), ignoring it",
2653 state.surface.get());
2654
Dominik Laskowski7e045462018-05-30 13:02:02 -07002655 displayId = state.type;
2656 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002657 producer = bqProducer;
2658 }
2659
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002660 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002661 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002662 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002663 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002665 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002666 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002667 if (mUseScheduler) {
2668 mScheduler->hotplugReceived(mAppConnectionHandle,
2669 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002670 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002671 } else {
2672 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2673 true);
2674 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002675 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002676 if (mUseScheduler) {
2677 mScheduler->hotplugReceived(mAppConnectionHandle,
2678 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002679 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002680 } else {
2681 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2682 true);
2683 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002684 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 }
2686 }
2687 }
2688 }
2689 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002690
2691 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002692}
2693
Mathias Agopian87baae12012-07-31 12:38:26 -07002694void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002695{
Dan Stoza7dde5992015-05-22 09:51:44 -07002696 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002697 mCurrentState.traverseInZOrder([](Layer* layer) {
2698 layer->notifyAvailableFrames();
2699 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002700
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002701 /*
2702 * Traversal of the children
2703 * (perform the transaction for each of them if needed)
2704 */
2705
Mathias Agopian3559b072012-08-15 13:46:03 -07002706 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002707 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002709 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710
2711 const uint32_t flags = layer->doTransaction(0);
2712 if (flags & Layer::eVisibleRegion)
2713 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002714 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715 }
2716
2717 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002718 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719 */
2720
Mathias Agopiane57f2922012-08-09 16:29:12 -07002721 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002723 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002726 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002727 // The transform hint might have changed for some layers
2728 // (either because a display has changed, or because a layer
2729 // as changed).
2730 //
2731 // Walk through all the layers in currentLayers,
2732 // and update their transform hint.
2733 //
2734 // If a layer is visible only on a single display, then that
2735 // display is used to calculate the hint, otherwise we use the
2736 // default display.
2737 //
2738 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2739 // the hint is set before we acquire a buffer from the surface texture.
2740 //
2741 // NOTE: layer transactions have taken place already, so we use their
2742 // drawing state. However, SurfaceFlinger's own transaction has not
2743 // happened yet, so we must use the current state layer list
2744 // (soon to become the drawing state list).
2745 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002747 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002748 bool first = true;
2749 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002750 // NOTE: we rely on the fact that layers are sorted by
2751 // layerStack first (so we don't have to traverse the list
2752 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002753 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002754 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002755 currentlayerStack = layerStack;
2756 // figure out if this layerstack is mirrored
2757 // (more than one display) if so, pick the default display,
2758 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002759 hintDisplay = nullptr;
2760 for (const auto& [token, display] : mDisplays) {
2761 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2762 if (hintDisplay) {
2763 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002764 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002765 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002766 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002767 }
2768 }
2769 }
2770 }
Chet Haase91d25932013-04-11 15:24:55 -07002771
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002772 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002773 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2774 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002775
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002776 // could be null when this layer is using a layerStack
2777 // that is not visible on any display. Also can occur at
2778 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002780 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002781
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002782 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002783 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002784 if (hintDisplay) {
2785 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002786 }
Robert Carr2047fae2016-11-28 14:09:09 -08002787
2788 first = false;
2789 });
Mathias Agopian84300952012-11-21 16:02:13 -08002790 }
2791
2792
Mathias Agopian3559b072012-08-15 13:46:03 -07002793 /*
2794 * Perform our own transaction if needed
2795 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002796
2797 if (mLayersAdded) {
2798 mLayersAdded = false;
2799 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002800 mVisibleRegionsDirty = true;
2801 }
2802
2803 // some layers might have been removed, so
2804 // we need to update the regions they're exposing.
2805 if (mLayersRemoved) {
2806 mLayersRemoved = false;
2807 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002808 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002809 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002810 // this layer is not visible anymore
2811 // TODO: we could traverse the tree from front to back and
2812 // compute the actual visible region
2813 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002814 Region visibleReg;
2815 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002816 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002817 }
Robert Carr2047fae2016-11-28 14:09:09 -08002818 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819 }
2820
2821 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002822
2823 updateCursorAsync();
2824}
2825
2826void SurfaceFlinger::updateCursorAsync()
2827{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002828 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002829 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002830 continue;
2831 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002833 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2834 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002835 }
2836 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002837}
2838
2839void SurfaceFlinger::commitTransaction()
2840{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002841 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002842 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002843 for (const auto& l : mLayersPendingRemoval) {
2844 recordBufferingStats(l->getName().string(),
2845 l->getOccupancyHistory(true));
2846 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002847 }
2848 mLayersPendingRemoval.clear();
2849 }
2850
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002851 // If this transaction is part of a window animation then the next frame
2852 // we composite should be considered an animation as well.
2853 mAnimCompositionPending = mAnimTransactionPending;
2854
Mathias Agopian4fec8732012-06-29 14:12:52 -07002855 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002856 // clear the "changed" flags in current state
2857 mCurrentState.colorMatrixChanged = false;
2858
Robert Carr1f0a16a2016-10-24 16:27:39 -07002859 mDrawingState.traverseInZOrder([](Layer* layer) {
2860 layer->commitChildList();
2861 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002862 mTransactionPending = false;
2863 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002864 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865}
2866
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002867void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2868 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002869 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002871
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002872 Region aboveOpaqueLayers;
2873 Region aboveCoveredLayers;
2874 Region dirty;
2875
Mathias Agopian87baae12012-07-31 12:38:26 -07002876 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002877
Robert Carr2047fae2016-11-28 14:09:09 -08002878 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002879 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002880 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881
Jesse Hall01e29052013-02-19 16:13:35 -08002882 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002883 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002884 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002885 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002886
Mathias Agopianab028732010-03-16 16:41:46 -07002887 /*
2888 * opaqueRegion: area of a surface that is fully opaque.
2889 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002891
2892 /*
2893 * visibleRegion: area of a surface that is visible on screen
2894 * and not fully transparent. This is essentially the layer's
2895 * footprint minus the opaque regions above it.
2896 * Areas covered by a translucent surface are considered visible.
2897 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002899
2900 /*
2901 * coveredRegion: area of a surface that is covered by all
2902 * visible regions above it (which includes the translucent areas).
2903 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002904 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002905
Jesse Halla8026d22012-09-25 13:25:04 -07002906 /*
2907 * transparentRegion: area of a surface that is hinted to be completely
2908 * transparent. This is only used to tell when the layer has no visible
2909 * non-transparent regions and can be removed from the layer list. It
2910 * does not affect the visibleRegion of this layer or any layers
2911 * beneath it. The hint may not be correct if apps don't respect the
2912 * SurfaceView restrictions (which, sadly, some don't).
2913 */
2914 Region transparentRegion;
2915
Mathias Agopianab028732010-03-16 16:41:46 -07002916
2917 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002918 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002919 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002921 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002922 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002923 if (!visibleRegion.isEmpty()) {
2924 // Remove the transparent area from the visible region
2925 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002926 if (tr.preserveRects()) {
2927 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002928 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002929 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002930 // transformation too complex, can't do the
2931 // transparent region optimization.
2932 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002933 }
Mathias Agopianab028732010-03-16 16:41:46 -07002934 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935
Mathias Agopianab028732010-03-16 16:41:46 -07002936 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002937 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002938 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002939 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002940 // the opaque region is the layer's footprint
2941 opaqueRegion = visibleRegion;
2942 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 }
2944 }
2945
Robert Carre5f4f692018-01-12 13:12:28 -08002946 if (visibleRegion.isEmpty()) {
2947 layer->clearVisibilityRegions();
2948 return;
2949 }
2950
Mathias Agopianab028732010-03-16 16:41:46 -07002951 // Clip the covered region to the visible region
2952 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2953
2954 // Update aboveCoveredLayers for next (lower) layer
2955 aboveCoveredLayers.orSelf(visibleRegion);
2956
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 // subtract the opaque region covered by the layers above us
2958 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959
2960 // compute this layer's dirty region
2961 if (layer->contentDirty) {
2962 // we need to invalidate the whole region
2963 dirty = visibleRegion;
2964 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002965 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002966 layer->contentDirty = false;
2967 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002968 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002969 * the exposed region consists of two components:
2970 * 1) what's VISIBLE now and was COVERED before
2971 * 2) what's EXPOSED now less what was EXPOSED before
2972 *
2973 * note that (1) is conservative, we start with the whole
2974 * visible region but only keep what used to be covered by
2975 * something -- which mean it may have been exposed.
2976 *
2977 * (2) handles areas that were not covered by anything but got
2978 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002979 */
Mathias Agopianab028732010-03-16 16:41:46 -07002980 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 const Region oldVisibleRegion = layer->visibleRegion;
2982 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002983 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2984 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985 }
2986 dirty.subtractSelf(aboveOpaqueLayers);
2987
2988 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002989 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990
Mathias Agopianab028732010-03-16 16:41:46 -07002991 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002993
Jesse Halla8026d22012-09-25 13:25:04 -07002994 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002995 layer->setVisibleRegion(visibleRegion);
2996 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002997 layer->setVisibleNonTransparentRegion(
2998 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002999 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003000
Mathias Agopian87baae12012-07-31 12:38:26 -07003001 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002}
3003
Chia-I Wuab0c3192017-08-01 11:29:00 -07003004void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003005 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003006 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3007 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003008 }
3009 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003010}
3011
Dan Stoza6b9454d2014-11-07 16:00:59 -08003012bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003014 ALOGV("handlePageFlip");
3015
Brian Andersond6927fb2016-07-23 23:37:30 -07003016 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003017
Mathias Agopian4fec8732012-06-29 14:12:52 -07003018 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003019 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003020 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003021
3022 // Store the set of layers that need updates. This set must not change as
3023 // buffers are being latched, as this could result in a deadlock.
3024 // Example: Two producers share the same command stream and:
3025 // 1.) Layer 0 is latched
3026 // 2.) Layer 0 gets a new frame
3027 // 2.) Layer 1 gets a new frame
3028 // 3.) Layer 1 is latched.
3029 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3030 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003031 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003032 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003033 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003034 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003035 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003036 } else {
3037 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003038 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003039 } else {
3040 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003041 }
Robert Carr2047fae2016-11-28 14:09:09 -08003042 });
3043
Dan Stoza9e56aa02015-11-02 13:00:03 -08003044 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07003045 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07003046 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003047 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003048 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003049 newDataLatched = true;
3050 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003051 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003052
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003053 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003054
3055 // If we will need to wake up at some time in the future to deal with a
3056 // queued frame that shouldn't be displayed during this vsync period, wake
3057 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003058 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003059 signalLayerUpdate();
3060 }
3061
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003062 // enter boot animation on first buffer latch
3063 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3064 ALOGI("Enter boot animation");
3065 mBootStage = BootStage::BOOTANIMATION;
3066 }
3067
Dan Stoza6b9454d2014-11-07 16:00:59 -08003068 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003069 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003070}
3071
Mathias Agopianad456f92011-01-13 17:53:01 -08003072void SurfaceFlinger::invalidateHwcGeometry()
3073{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003074 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003075}
3076
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003077void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3078 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003079 // We only need to actually compose the display if:
3080 // 1) It is being handled by hardware composer, which may need this to
3081 // keep its virtual display state machine in sync, or
3082 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003083 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003084 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003085 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003086 return;
3087 }
3088
Dan Stoza9e56aa02015-11-02 13:00:03 -08003089 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003090 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003091
3092 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003093 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003094}
3095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003096bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003097 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003099 const Region bounds(display->bounds());
3100 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003101 const auto displayId = display->getId();
3102 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003103 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003104
Chia-I Wu8e50e692018-05-04 10:12:37 -07003105 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003106 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003107
Dan Stoza9e56aa02015-11-02 13:00:03 -08003108 if (hasClientComposition) {
3109 ALOGV("hasClientComposition");
3110
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003111 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003112 if (display->hasWideColorGamut()) {
3113 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003114 }
3115 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003116 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003117 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003118
Dominik Laskowski7e045462018-05-30 13:02:02 -07003119 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003120 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3121 HWC2::Capability::SkipClientColorTransform);
3122
Chia-I Wud49d6692018-06-27 07:17:41 +08003123 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003124 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3125 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003126 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003127 }
3128
Chia-I Wud49d6692018-06-27 07:17:41 +08003129 // The current enhanced saturation matrix is designed to enhance Display P3,
3130 // thus we only apply this matrix when the render intent is not colorimetric
3131 // and the output color space is Display P3.
3132 needsEnhancedColorMatrix =
3133 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3134 outputDataspace == Dataspace::DISPLAY_P3);
3135 if (needsEnhancedColorMatrix) {
3136 colorMatrix *= mEnhancedSaturationMatrix;
3137 }
3138
3139 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003140
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003141 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003142 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003143 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003144 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003145
3146 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003147 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3148 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3149 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003150 }
3151 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003152 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003153
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003154 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003155 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003156 // when using overlays, we assume a fully transparent framebuffer
3157 // NOTE: we could reduce how much we need to clear, for instance
3158 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003159 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003160 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003161 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003162 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003163 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003164 // we're left with the letterbox region
3165 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003166 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003167
3168 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003169 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003170
Mathias Agopianb9494d52012-04-18 02:28:45 -07003171 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003172 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003173 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003174 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003175 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003176 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003177
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003178 const Rect& bounds = display->getBounds();
3179 const Rect& scissor = display->getScissor();
3180 if (scissor != bounds) {
3181 // scissor doesn't match the screen's dimensions, so we
3182 // need to clear everything outside of it and enable
3183 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003184
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003185 // enable scissor for this frame
3186 const uint32_t height = display->getHeight();
3187 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
3188 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003189 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003190 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003191
Mathias Agopian85d751c2012-08-29 16:59:24 -07003192 /*
3193 * and then, render the layers targeted at the framebuffer
3194 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003195
Dan Stoza9e56aa02015-11-02 13:00:03 -08003196 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003197 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003198 bool firstLayer = true;
David Sodmanfb95bcc2017-12-22 15:45:30 -08003199 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
3200 const Region bounds(display->bounds());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003201 const Region clip(bounds.intersect(
David Sodmanfb95bcc2017-12-22 15:45:30 -08003202 displayTransform.transform(compositionInfo.layer->mLayer->visibleRegion)));
3203 ALOGV("Layer: %s", compositionInfo.layerName.c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003204 if (!clip.isEmpty()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003205 switch (compositionInfo.compositionType) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003206 case HWC2::Composition::Cursor:
3207 case HWC2::Composition::Device:
3208 case HWC2::Composition::Sideband:
3209 case HWC2::Composition::SolidColor: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003210 const Layer::State& state(compositionInfo.layer->mLayer->getDrawingState());
3211 const bool opaque = compositionInfo.layer->mLayer->isOpaque(state);
3212 if (compositionInfo.hwc.clearClientTarget && !firstLayer &&
3213 opaque && (state.color.a == 1.0f) && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003214 // never clear the very first layer since we're
3215 // guaranteed the FB is already cleared
David Sodman10a41ff2018-08-05 12:14:17 -07003216 compositionInfo.layer->clear(getRenderEngine());
Mathias Agopiancd60f992012-08-16 16:28:27 -07003217 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003218 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003219 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003220 case HWC2::Composition::Client: {
David Sodmanfb95bcc2017-12-22 15:45:30 -08003221 compositionInfo.layer->mLayer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003222 break;
3223 }
3224 default:
3225 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003226 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003227 } else {
3228 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003229 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003230 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003231 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003232
Chia-I Wud49d6692018-06-27 07:17:41 +08003233 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003234 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003235 }
3236
Mathias Agopianf45c5102012-10-24 16:29:17 -07003237 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003238 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003239 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240}
3241
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003242void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3243 const Region& region) const {
3244 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003245 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003246 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247}
3248
Dan Stoza7d89d062015-04-30 13:29:25 -07003249status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003250 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003251 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003252 const sp<Layer>& lbc,
3253 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003254{
Dan Stoza7d89d062015-04-30 13:29:25 -07003255 // add this layer to the current state list
3256 {
3257 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003258 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003259 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3260 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003261 return NO_MEMORY;
3262 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003263 if (parent == nullptr) {
3264 mCurrentState.layersSortedByZ.add(lbc);
3265 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003266 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003267 ALOGE("addClientLayer called with a removed parent");
3268 return NAME_NOT_FOUND;
3269 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003270 parent->addChild(lbc);
3271 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003272
Yiwei Zhang243b3782018-05-15 17:40:04 -07003273 if (gbc != nullptr) {
3274 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3275 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3276 mMaxGraphicBufferProducerListSize,
3277 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3278 mGraphicBufferProducerList.size(),
3279 mMaxGraphicBufferProducerListSize, mNumLayers);
3280 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003281 mLayersAdded = true;
3282 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003283 }
3284
Mathias Agopian96f08192010-06-02 23:28:45 -07003285 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003286 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003287
Dan Stoza7d89d062015-04-30 13:29:25 -07003288 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003289}
3290
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003291status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003292 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003293 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3294}
Robert Carr7f9b8992017-03-10 11:08:39 -08003295
chaviwca27f252018-02-06 16:46:39 -08003296status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3297 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003298 if (layer->isPendingRemoval()) {
3299 return NO_ERROR;
3300 }
3301
Robert Carr1f0a16a2016-10-24 16:27:39 -07003302 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003303 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003304 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003305 if (topLevelOnly) {
3306 return NO_ERROR;
3307 }
3308
Chia-I Wu98f1c102017-05-30 14:54:08 -07003309 sp<Layer> ancestor = p;
3310 while (ancestor->getParent() != nullptr) {
3311 ancestor = ancestor->getParent();
3312 }
3313 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3314 ALOGE("removeLayer called with a layer whose parent has been removed");
3315 return NAME_NOT_FOUND;
3316 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003317
3318 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003319 } else {
3320 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003321 }
3322
Robert Carr136e2f62017-02-08 17:54:29 -08003323 // As a matter of normal operation, the LayerCleaner will produce a second
3324 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3325 // so we will succeed in promoting it, but it's already been removed
3326 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3327 // otherwise something has gone wrong and we are leaking the layer.
3328 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003329 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3330 layer->getName().string(),
3331 (p != nullptr) ? p->getName().string() : "no-parent");
3332 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003333 } else if (index < 0) {
3334 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003335 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003336
Chia-I Wuc6657022017-08-15 11:18:17 -07003337 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003338 mLayersPendingRemoval.add(layer);
3339 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003340 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003341 setTransactionFlags(eTransactionNeeded);
3342 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003343}
3344
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003345uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003346 return android_atomic_release_load(&mTransactionFlags);
3347}
3348
Mathias Agopian3f844832013-08-07 21:24:32 -07003349uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003350 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3351}
3352
Mathias Agopian3f844832013-08-07 21:24:32 -07003353uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003354 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3355}
3356
3357uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3358 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003359 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003360 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003361 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003362 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003363 }
3364 return old;
3365}
3366
chaviwca27f252018-02-06 16:46:39 -08003367bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3368 for (const ComposerState& state : states) {
3369 // Here we need to check that the interface we're given is indeed
3370 // one of our own. A malicious client could give us a nullptr
3371 // IInterface, or one of its own or even one of our own but a
3372 // different type. All these situations would cause us to crash.
3373 if (state.client == nullptr) {
3374 return true;
3375 }
3376
3377 sp<IBinder> binder = IInterface::asBinder(state.client);
3378 if (binder == nullptr) {
3379 return true;
3380 }
3381
3382 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3383 return true;
3384 }
3385 }
3386 return false;
3387}
3388
Mathias Agopian8b33f032012-07-24 20:43:54 -07003389void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003390 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003391 const Vector<DisplayState>& displays,
3392 uint32_t flags)
3393{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003394 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003395 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003396 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003397
chaviwca27f252018-02-06 16:46:39 -08003398 if (containsAnyInvalidClientState(states)) {
3399 return;
3400 }
3401
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003402 if (flags & eAnimation) {
3403 // For window updates that are part of an animation we must wait for
3404 // previous animation "frames" to be handled.
3405 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003406 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003407 if (CC_UNLIKELY(err != NO_ERROR)) {
3408 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003409 // caller after a few seconds.
3410 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3411 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003412 mAnimTransactionPending = false;
3413 break;
3414 }
3415 }
3416 }
3417
chaviwca27f252018-02-06 16:46:39 -08003418 for (const DisplayState& display : displays) {
3419 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003420 }
3421
chaviwca27f252018-02-06 16:46:39 -08003422 for (const ComposerState& state : states) {
3423 transactionFlags |= setClientStateLocked(state);
3424 }
3425
3426 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3427 // as destroyed should only occur after setting all other states. This is to allow for a
3428 // child re-parent to happen before marking its original parent as destroyed (which would
3429 // then mark the child as destroyed).
3430 for (const ComposerState& state : states) {
3431 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003432 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003433
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003434 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3435 // anyway. This can be used as a flush mechanism for previous async transactions.
3436 // Empty animation transaction can be used to simulate back-pressure, so also force a
3437 // transaction for empty animation transactions.
3438 if (transactionFlags == 0 &&
3439 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003440 transactionFlags = eTransactionNeeded;
3441 }
3442
Mathias Agopian386aa982011-11-07 21:58:03 -08003443 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003444 if (mInterceptor->isEnabled()) {
3445 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003446 }
Irvel468051e2016-06-13 16:44:44 -07003447
Mathias Agopian386aa982011-11-07 21:58:03 -08003448 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003449 const auto start = (flags & eEarlyWakeup)
3450 ? VSyncModulator::TransactionStart::EARLY
3451 : VSyncModulator::TransactionStart::NORMAL;
3452 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003453
3454 // if this is a synchronous transaction, wait for it to take effect
3455 // before returning.
3456 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003457 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003458 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003459 if (flags & eAnimation) {
3460 mAnimTransactionPending = true;
3461 }
3462 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003463 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3464 if (CC_UNLIKELY(err != NO_ERROR)) {
3465 // just in case something goes wrong in SF, return to the
3466 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003467 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3468 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003469 break;
3470 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003471 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472 }
3473}
3474
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003475uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3476 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3477 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003478
Mathias Agopiane57f2922012-08-09 16:29:12 -07003479 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003480 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3481
3482 const uint32_t what = s.what;
3483 if (what & DisplayState::eSurfaceChanged) {
3484 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3485 state.surface = s.surface;
3486 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003487 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003488 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003489 if (what & DisplayState::eLayerStackChanged) {
3490 if (state.layerStack != s.layerStack) {
3491 state.layerStack = s.layerStack;
3492 flags |= eDisplayTransactionNeeded;
3493 }
3494 }
3495 if (what & DisplayState::eDisplayProjectionChanged) {
3496 if (state.orientation != s.orientation) {
3497 state.orientation = s.orientation;
3498 flags |= eDisplayTransactionNeeded;
3499 }
3500 if (state.frame != s.frame) {
3501 state.frame = s.frame;
3502 flags |= eDisplayTransactionNeeded;
3503 }
3504 if (state.viewport != s.viewport) {
3505 state.viewport = s.viewport;
3506 flags |= eDisplayTransactionNeeded;
3507 }
3508 }
3509 if (what & DisplayState::eDisplaySizeChanged) {
3510 if (state.width != s.width) {
3511 state.width = s.width;
3512 flags |= eDisplayTransactionNeeded;
3513 }
3514 if (state.height != s.height) {
3515 state.height = s.height;
3516 flags |= eDisplayTransactionNeeded;
3517 }
3518 }
3519
Mathias Agopiane57f2922012-08-09 16:29:12 -07003520 return flags;
3521}
3522
Robert Carrd4ae7f32018-06-07 16:10:57 -07003523bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3524 IPCThreadState* ipc = IPCThreadState::self();
3525 const int pid = ipc->getCallingPid();
3526 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003527 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003528 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003529 return false;
3530 }
3531 return true;
3532}
3533
chaviwca27f252018-02-06 16:46:39 -08003534uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3535 const layer_state_t& s = composerState.state;
3536 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3537
Mathias Agopian13127d82013-03-05 17:47:11 -08003538 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003539 if (layer == nullptr) {
3540 return 0;
3541 }
3542
3543 if (layer->isPendingRemoval()) {
3544 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3545 return 0;
3546 }
3547
3548 uint32_t flags = 0;
3549
3550 const uint32_t what = s.what;
3551 bool geometryAppliesWithResize =
3552 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003553
3554 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3555 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003556 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003557 layer->pushPendingState();
3558 }
3559
chaviw8b3871a2017-11-01 17:41:01 -07003560 if (what & layer_state_t::ePositionChanged) {
3561 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3562 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003563 }
chaviw8b3871a2017-11-01 17:41:01 -07003564 }
3565 if (what & layer_state_t::eLayerChanged) {
3566 // NOTE: index needs to be calculated before we update the state
3567 const auto& p = layer->getParent();
3568 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003569 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003570 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003571 mCurrentState.layersSortedByZ.removeAt(idx);
3572 mCurrentState.layersSortedByZ.add(layer);
3573 // we need traversal (state changed)
3574 // AND transaction (list changed)
3575 flags |= eTransactionNeeded|eTraversalNeeded;
3576 }
chaviw8b3871a2017-11-01 17:41:01 -07003577 } else {
3578 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003579 flags |= eTransactionNeeded|eTraversalNeeded;
3580 }
3581 }
chaviw8b3871a2017-11-01 17:41:01 -07003582 }
3583 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003584 // NOTE: index needs to be calculated before we update the state
3585 const auto& p = layer->getParent();
3586 if (p == nullptr) {
3587 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3588 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3589 mCurrentState.layersSortedByZ.removeAt(idx);
3590 mCurrentState.layersSortedByZ.add(layer);
3591 // we need traversal (state changed)
3592 // AND transaction (list changed)
3593 flags |= eTransactionNeeded|eTraversalNeeded;
3594 }
3595 } else {
3596 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3597 flags |= eTransactionNeeded|eTraversalNeeded;
3598 }
chaviw8b3871a2017-11-01 17:41:01 -07003599 }
3600 }
3601 if (what & layer_state_t::eSizeChanged) {
3602 if (layer->setSize(s.w, s.h)) {
3603 flags |= eTraversalNeeded;
3604 }
3605 }
3606 if (what & layer_state_t::eAlphaChanged) {
3607 if (layer->setAlpha(s.alpha))
3608 flags |= eTraversalNeeded;
3609 }
3610 if (what & layer_state_t::eColorChanged) {
3611 if (layer->setColor(s.color))
3612 flags |= eTraversalNeeded;
3613 }
3614 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003615 // TODO: b/109894387
3616 //
3617 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3618 // rotation. To see the problem observe that if we have a square parent, and a child
3619 // of the same size, then we rotate the child 45 degrees around it's center, the child
3620 // must now be cropped to a non rectangular 8 sided region.
3621 //
3622 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3623 // private API, and the WindowManager only uses rotation in one case, which is on a top
3624 // level layer in which cropping is not an issue.
3625 //
3626 // However given that abuse of rotation matrices could lead to surfaces extending outside
3627 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3628 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3629 // transformations.
3630 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003631 flags |= eTraversalNeeded;
3632 }
3633 if (what & layer_state_t::eTransparentRegionChanged) {
3634 if (layer->setTransparentRegionHint(s.transparentRegion))
3635 flags |= eTraversalNeeded;
3636 }
3637 if (what & layer_state_t::eFlagsChanged) {
3638 if (layer->setFlags(s.flags, s.mask))
3639 flags |= eTraversalNeeded;
3640 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003641 if (what & layer_state_t::eCropChanged_legacy) {
3642 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003643 flags |= eTraversalNeeded;
3644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 if (what & layer_state_t::eLayerStackChanged) {
3646 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3647 // We only allow setting layer stacks for top level layers,
3648 // everything else inherits layer stack from its parent.
3649 if (layer->hasParent()) {
3650 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3651 layer->getName().string());
3652 } else if (idx < 0) {
3653 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3654 "that also does not appear in the top level layer list. Something"
3655 " has gone wrong.", layer->getName().string());
3656 } else if (layer->setLayerStack(s.layerStack)) {
3657 mCurrentState.layersSortedByZ.removeAt(idx);
3658 mCurrentState.layersSortedByZ.add(layer);
3659 // we need traversal (state changed)
3660 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003661 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003662 }
3663 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003664 if (what & layer_state_t::eDeferTransaction_legacy) {
3665 if (s.barrierHandle_legacy != nullptr) {
3666 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3667 } else if (s.barrierGbp_legacy != nullptr) {
3668 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003669 if (authenticateSurfaceTextureLocked(gbp)) {
3670 const auto& otherLayer =
3671 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003672 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003673 } else {
3674 ALOGE("Attempt to defer transaction to to an"
3675 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003676 }
3677 }
chaviw8b3871a2017-11-01 17:41:01 -07003678 // We don't trigger a traversal here because if no other state is
3679 // changed, we don't want this to cause any more work
3680 }
3681 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003682 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003683 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003684 if (!hadParent) {
3685 mCurrentState.layersSortedByZ.remove(layer);
3686 }
chaviw8b3871a2017-11-01 17:41:01 -07003687 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003688 }
chaviw8b3871a2017-11-01 17:41:01 -07003689 }
3690 if (what & layer_state_t::eReparentChildren) {
3691 if (layer->reparentChildren(s.reparentHandle)) {
3692 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003693 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003694 }
chaviw8b3871a2017-11-01 17:41:01 -07003695 if (what & layer_state_t::eDetachChildren) {
3696 layer->detachChildren();
3697 }
3698 if (what & layer_state_t::eOverrideScalingModeChanged) {
3699 layer->setOverrideScalingMode(s.overrideScalingMode);
3700 // We don't trigger a traversal here because if no other state is
3701 // changed, we don't want this to cause any more work
3702 }
Marissa Wall61c58622018-07-18 10:12:20 -07003703 if (what & layer_state_t::eTransformChanged) {
3704 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3705 }
3706 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3707 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3708 flags |= eTraversalNeeded;
3709 }
3710 if (what & layer_state_t::eCropChanged) {
3711 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3712 }
3713 if (what & layer_state_t::eBufferChanged) {
3714 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3715 }
3716 if (what & layer_state_t::eAcquireFenceChanged) {
3717 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3718 }
3719 if (what & layer_state_t::eDataspaceChanged) {
3720 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3721 }
3722 if (what & layer_state_t::eHdrMetadataChanged) {
3723 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3724 }
3725 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3726 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3727 }
3728 if (what & layer_state_t::eApiChanged) {
3729 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3730 }
3731 if (what & layer_state_t::eSidebandStreamChanged) {
3732 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3733 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003734 return flags;
3735}
3736
chaviwca27f252018-02-06 16:46:39 -08003737void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3738 const layer_state_t& state = composerState.state;
3739 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3740
3741 sp<Layer> layer(client->getLayerUser(state.surface));
3742 if (layer == nullptr) {
3743 return;
3744 }
3745
3746 if (layer->isPendingRemoval()) {
3747 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3748 return;
3749 }
3750
3751 if (state.what & layer_state_t::eDestroySurface) {
3752 removeLayerLocked(mStateLock, layer);
3753 }
3754}
3755
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003756status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003757 const String8& name,
3758 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003759 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003760 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003761 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003762{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003763 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003764 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003765 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003766 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003767 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003768
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003769 status_t result = NO_ERROR;
3770
3771 sp<Layer> layer;
3772
Cody Northropbc755282017-03-31 12:00:08 -06003773 String8 uniqueName = getUniqueLayerName(name);
3774
Mathias Agopian3165cc22012-08-08 19:42:09 -07003775 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003776 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003777 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3778 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003779
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003780 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003781 case ISurfaceComposerClient::eFXSurfaceBufferState:
3782 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3783 break;
chaviw13fdc492017-06-27 12:40:18 -07003784 case ISurfaceComposerClient::eFXSurfaceColor:
3785 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003786 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003787 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003788 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003789 case ISurfaceComposerClient::eFXSurfaceContainer:
3790 result = createContainerLayer(client,
3791 uniqueName, w, h, flags,
3792 handle, &layer);
3793 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003794 default:
3795 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 break;
3797 }
3798
Dan Stoza7d89d062015-04-30 13:29:25 -07003799 if (result != NO_ERROR) {
3800 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003801 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003802
Chia-I Wuab0c3192017-08-01 11:29:00 -07003803 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3804 // TODO b/64227542
3805 if (windowType == 441731) {
3806 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3807 layer->setPrimaryDisplayOnly();
3808 }
3809
Albert Chaulk479c60c2017-01-27 14:21:34 -05003810 layer->setInfo(windowType, ownerUid);
3811
Robert Carr1f0a16a2016-10-24 16:27:39 -07003812 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003813 if (result != NO_ERROR) {
3814 return result;
3815 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003816 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003817
3818 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003819 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003820}
3821
Cody Northropbc755282017-03-31 12:00:08 -06003822String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3823{
3824 bool matchFound = true;
3825 uint32_t dupeCounter = 0;
3826
3827 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3828 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3829
Dan Stoza436ccf32018-06-21 12:10:12 -07003830 // Grab the state lock since we're accessing mCurrentState
3831 Mutex::Autolock lock(mStateLock);
3832
Cody Northropbc755282017-03-31 12:00:08 -06003833 // Loop over layers until we're sure there is no matching name
3834 while (matchFound) {
3835 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003836 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003837 if (layer->getName() == uniqueName) {
3838 matchFound = true;
3839 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3840 }
3841 });
3842 }
3843
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003844 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3845 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003846
3847 return uniqueName;
3848}
3849
Marissa Wallfd668622018-05-10 10:21:13 -07003850status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3851 uint32_t w, uint32_t h, uint32_t flags,
3852 PixelFormat& format, sp<IBinder>* handle,
3853 sp<IGraphicBufferProducer>* gbp,
3854 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003855 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003856 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003857 case PIXEL_FORMAT_TRANSPARENT:
3858 case PIXEL_FORMAT_TRANSLUCENT:
3859 format = PIXEL_FORMAT_RGBA_8888;
3860 break;
3861 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003862 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003863 break;
3864 }
3865
Marissa Wallfd668622018-05-10 10:21:13 -07003866 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3867 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003868 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003869 *handle = layer->getHandle();
3870 *gbp = layer->getProducer();
3871 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003873
Marissa Wallfd668622018-05-10 10:21:13 -07003874 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003875 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003876}
3877
Marissa Wall61c58622018-07-18 10:12:20 -07003878status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3879 uint32_t w, uint32_t h, uint32_t flags,
3880 sp<IBinder>* handle, sp<Layer>* outLayer) {
3881 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3882 *handle = layer->getHandle();
3883 *outLayer = layer;
3884
3885 return NO_ERROR;
3886}
3887
chaviw13fdc492017-06-27 12:40:18 -07003888status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003889 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003890 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003891{
chaviw13fdc492017-06-27 12:40:18 -07003892 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003893 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003894 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003895}
3896
Robert Carr6b3f6c52018-08-13 13:05:17 -07003897status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3898 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3899 sp<IBinder>* handle, sp<Layer>* outLayer)
3900{
3901 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3902 *handle = (*outLayer)->getHandle();
3903 return NO_ERROR;
3904}
3905
3906
Mathias Agopianac9fa422013-02-11 16:40:36 -08003907status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908{
Robert Carr9524cb32017-02-13 11:32:32 -08003909 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003910 status_t err = NO_ERROR;
3911 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003912 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003913 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003914 err = removeLayer(l);
3915 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3916 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003917 }
3918 return err;
3919}
3920
Mathias Agopian13127d82013-03-05 17:47:11 -08003921status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003922{
Mathias Agopian67106042013-03-14 19:18:13 -07003923 // called by ~LayerCleaner() when all references to the IBinder (handle)
3924 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003925 sp<Layer> l = layer.promote();
3926 if (l == nullptr) {
3927 // The layer has already been removed, carry on
3928 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003929 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003930 // If we have a parent, then we can continue to live as long as it does.
3931 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932}
3933
Mathias Agopianb60314a2012-04-10 22:09:54 -07003934// ---------------------------------------------------------------------------
3935
Andy McFadden13a082e2012-08-24 10:16:42 -07003936void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003937 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3938 if (!displayToken) return;
3939
Jesse Hall01e29052013-02-19 16:13:35 -08003940 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003941 Vector<ComposerState> state;
3942 Vector<DisplayState> displays;
3943 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003944 d.what = DisplayState::eDisplayProjectionChanged |
3945 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003946 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003947 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003948 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003949 d.frame.makeInvalid();
3950 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003951 d.width = 0;
3952 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003953 displays.add(d);
3954 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003955
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003956 const auto display = getDisplayDevice(displayToken);
3957 if (!display) return;
3958
3959 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3960
3961 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003962 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003963 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003964
Brian Andersond0010582017-03-07 13:20:31 -08003965 // Use phase of 0 since phase is not known.
3966 // Use latency of 0, which will snap to the ideal latency.
3967 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003968}
3969
3970void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003971 // Async since we may be called from the main thread.
3972 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003973}
3974
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003975void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3976 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003977 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003978 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003980 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003981 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003982 return;
3983 }
3984
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003986 ALOGW("Trying to set power mode for virtual display");
3987 return;
3988 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003989
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003990 display->setPowerMode(mode);
3991
Lloyd Pique4dccc412018-01-22 17:21:36 -08003992 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003993 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003995 if (idx < 0) {
3996 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3997 return;
3998 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003999 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004000 }
4001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004002 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004003 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004004 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004005 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004006 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004007 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004008 if (mUseScheduler) {
4009 mScheduler->onScreenAcquired(mAppConnectionHandle);
4010 } else {
4011 mEventThread->onScreenAcquired();
4012 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004013 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004014 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004016 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004017 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004018 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004019
4020 struct sched_param param = {0};
4021 param.sched_priority = 1;
4022 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4023 ALOGW("Couldn't set SCHED_FIFO on display on");
4024 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004025 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004026 // Turn off the display
4027 struct sched_param param = {0};
4028 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4029 ALOGW("Couldn't set SCHED_OTHER on display off");
4030 }
4031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004032 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004033 disableHardwareVsync(true); // also cancels any in-progress resync
4034
Mathias Agopiancde87a32012-09-13 14:09:01 -07004035 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004036 if (mUseScheduler) {
4037 mScheduler->onScreenReleased(mAppConnectionHandle);
4038 } else {
4039 mEventThread->onScreenReleased();
4040 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004041 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004042
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004043 getHwComposer().setPowerMode(type, mode);
4044 mVisibleRegionsDirty = true;
4045 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004046 } else if (mode == HWC_POWER_MODE_DOZE ||
4047 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004048 // Update display while dozing
4049 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004050 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004051 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004052 if (mUseScheduler) {
4053 mScheduler->onScreenAcquired(mAppConnectionHandle);
4054 } else {
4055 mEventThread->onScreenAcquired();
4056 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004057 resyncToHardwareVsync(true);
4058 }
4059 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4060 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004061 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004062 disableHardwareVsync(true); // also cancels any in-progress resync
4063 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004064 if (mUseScheduler) {
4065 mScheduler->onScreenReleased(mAppConnectionHandle);
4066 } else {
4067 mEventThread->onScreenReleased();
4068 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004069 }
4070 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004071 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004072 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004073 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004074 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004075
4076 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004077}
4078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004079void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004080 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004081 const auto display = getDisplayDevice(displayToken);
4082 if (!display) {
4083 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4084 displayToken.get());
4085 } else if (display->isVirtual()) {
4086 ALOGW("Attempt to set power mode %d for virtual display", mode);
4087 } else {
4088 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004089 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004090 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004091}
4092
4093// ---------------------------------------------------------------------------
4094
Lloyd Pique755e3192018-01-31 16:46:15 -08004095status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4096 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004097 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004098
Mathias Agopianbd115332013-04-18 16:41:04 -07004099 IPCThreadState* ipc = IPCThreadState::self();
4100 const int pid = ipc->getCallingPid();
4101 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004102
Mathias Agopianbd115332013-04-18 16:41:04 -07004103 if ((uid != AID_SHELL) &&
4104 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004105 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004106 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004107 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004108 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004109 // (this would indicate SF is stuck, but we want to be able to
4110 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004111 status_t err = mStateLock.timedLock(s2ns(1));
4112 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004113 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004114 result.appendFormat(
4115 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4116 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004117 }
4118
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004119 bool dumpAll = true;
4120 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004121 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004122
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004123 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004124 if ((index < numArgs) &&
4125 (args[index] == String16("--list"))) {
4126 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004127 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004128 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004129 }
4130
4131 if ((index < numArgs) &&
4132 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004133 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004134 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004135 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004136 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004137
4138 if ((index < numArgs) &&
4139 (args[index] == String16("--latency-clear"))) {
4140 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004141 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004142 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004143 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004144
4145 if ((index < numArgs) &&
4146 (args[index] == String16("--dispsync"))) {
4147 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004148 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004149 dumpAll = false;
4150 }
Dan Stozab90cf072015-03-05 11:05:59 -08004151
4152 if ((index < numArgs) &&
4153 (args[index] == String16("--static-screen"))) {
4154 index++;
4155 dumpStaticScreenStats(result);
4156 dumpAll = false;
4157 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004158
4159 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004160 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004161 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004162 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004163 dumpAll = false;
4164 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004165
4166 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4167 index++;
4168 dumpWideColorInfo(result);
4169 dumpAll = false;
4170 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004171
4172 if ((index < numArgs) &&
4173 (args[index] == String16("--enable-layer-stats"))) {
4174 index++;
4175 mLayerStats.enable();
4176 dumpAll = false;
4177 }
4178
4179 if ((index < numArgs) &&
4180 (args[index] == String16("--disable-layer-stats"))) {
4181 index++;
4182 mLayerStats.disable();
4183 dumpAll = false;
4184 }
4185
4186 if ((index < numArgs) &&
4187 (args[index] == String16("--clear-layer-stats"))) {
4188 index++;
4189 mLayerStats.clear();
4190 dumpAll = false;
4191 }
4192
4193 if ((index < numArgs) &&
4194 (args[index] == String16("--dump-layer-stats"))) {
4195 index++;
4196 mLayerStats.dump(result);
4197 dumpAll = false;
4198 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004199
4200 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004201 (args[index] == String16("--frame-composition"))) {
4202 index++;
4203 dumpFrameCompositionInfo(result);
4204 dumpAll = false;
4205 }
4206
4207 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004208 (args[index] == String16("--display-identification"))) {
4209 index++;
4210 dumpDisplayIdentificationData(result);
4211 dumpAll = false;
4212 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004213
4214 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4215 index++;
4216 mTimeStats.parseArgs(asProto, args, index, result);
4217 dumpAll = false;
4218 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004219 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004220
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004221 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004222 if (asProto) {
4223 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4224 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4225 } else {
4226 dumpAllLocked(args, index, result);
4227 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004228 }
4229
Mathias Agopian9795c422009-08-26 16:36:26 -07004230 if (locked) {
4231 mStateLock.unlock();
4232 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004233 }
4234 write(fd, result.string(), result.size());
4235 return NO_ERROR;
4236}
4237
Dan Stozac7014012014-02-14 15:03:43 -08004238void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4239 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004240{
Robert Carr2047fae2016-11-28 14:09:09 -08004241 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004242 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004243 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004244}
4245
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004247 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248{
4249 String8 name;
4250 if (index < args.size()) {
4251 name = String8(args[index]);
4252 index++;
4253 }
4254
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004255 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4256 getHwComposer().isConnected(displayId)) {
4257 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4258 const nsecs_t period = activeConfig->getVsyncPeriod();
4259 result.appendFormat("%" PRId64 "\n", period);
4260 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004261
4262 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004263 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004264 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004265 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004266 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004267 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004268 }
Robert Carr2047fae2016-11-28 14:09:09 -08004269 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270 }
4271}
4272
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004273void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004274 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004275{
4276 String8 name;
4277 if (index < args.size()) {
4278 name = String8(args[index]);
4279 index++;
4280 }
4281
Robert Carr2047fae2016-11-28 14:09:09 -08004282 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004283 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004284 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004285 }
Robert Carr2047fae2016-11-28 14:09:09 -08004286 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004287
Svetoslavd85084b2014-03-20 10:28:31 -07004288 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004289}
4290
Jamie Gennis6547ff42013-07-16 20:12:42 -07004291// This should only be called from the main thread. Otherwise it would need
4292// the lock and should use mCurrentState rather than mDrawingState.
4293void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004294 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004295 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004296 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004297
4298 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4299}
4300
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004301void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004302{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004303 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004304
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004305 if (isLayerTripleBufferingDisabled())
4306 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004307
4308 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004309 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004310 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004311 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004312 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4313 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004314 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004315}
4316
Dan Stozab90cf072015-03-05 11:05:59 -08004317void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4318{
4319 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004320 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4321 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004322 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004323 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004324 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4325 b + 1, bucketTimeSec, percent);
4326 }
David Sodman4a36e932017-11-07 14:29:47 -08004327 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004328 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004329 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004330 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004331 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004332}
4333
Dan Stozae77c7662016-05-13 11:37:28 -07004334void SurfaceFlinger::recordBufferingStats(const char* layerName,
4335 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004336 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4337 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004338 for (const auto& segment : history) {
4339 if (!segment.usedThirdBuffer) {
4340 stats.twoBufferTime += segment.totalTime;
4341 }
4342 if (segment.occupancyAverage < 1.0f) {
4343 stats.doubleBufferedTime += segment.totalTime;
4344 } else if (segment.occupancyAverage < 2.0f) {
4345 stats.tripleBufferedTime += segment.totalTime;
4346 }
4347 ++stats.numSegments;
4348 stats.totalTime += segment.totalTime;
4349 }
4350}
4351
Brian Andersond6927fb2016-07-23 23:37:30 -07004352void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4353 result.appendFormat("Layer frame timestamps:\n");
4354
4355 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4356 const size_t count = currentLayers.size();
4357 for (size_t i=0 ; i<count ; i++) {
4358 currentLayers[i]->dumpFrameEvents(result);
4359 }
4360}
4361
Dan Stozae77c7662016-05-13 11:37:28 -07004362void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4363 result.append("Buffering stats:\n");
4364 result.append(" [Layer name] <Active time> <Two buffer> "
4365 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004366 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004367 typedef std::tuple<std::string, float, float, float> BufferTuple;
4368 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004369 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004370 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004371 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004372 if (stats.numSegments == 0) {
4373 continue;
4374 }
4375 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4376 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4377 stats.totalTime;
4378 float doubleBufferRatio = static_cast<float>(
4379 stats.doubleBufferedTime) / stats.totalTime;
4380 float tripleBufferRatio = static_cast<float>(
4381 stats.tripleBufferedTime) / stats.totalTime;
4382 sorted.insert({activeTime, {name, twoBufferRatio,
4383 doubleBufferRatio, tripleBufferRatio}});
4384 }
4385 for (const auto& sortedPair : sorted) {
4386 float activeTime = sortedPair.first;
4387 const BufferTuple& values = sortedPair.second;
4388 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4389 std::get<0>(values).c_str(), activeTime,
4390 std::get<1>(values), std::get<2>(values),
4391 std::get<3>(values));
4392 }
4393 result.append("\n");
4394}
4395
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004396void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004397 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004398 const int32_t displayId = display->getId();
4399 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4400 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004401 continue;
4402 }
4403
Dominik Laskowski7e045462018-05-30 13:02:02 -07004404 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004405 uint8_t port;
4406 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004407 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004408 result.append("no identification data\n");
4409 continue;
4410 }
4411
4412 if (!isEdid(data)) {
4413 result.append("unknown identification data: ");
4414 for (uint8_t byte : data) {
4415 result.appendFormat("%x ", byte);
4416 }
4417 result.append("\n");
4418 continue;
4419 }
4420
4421 const auto edid = parseEdid(data);
4422 if (!edid) {
4423 result.append("invalid EDID: ");
4424 for (uint8_t byte : data) {
4425 result.appendFormat("%x ", byte);
4426 }
4427 result.append("\n");
4428 continue;
4429 }
4430
4431 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4432 result.append(edid->displayName.data(), edid->displayName.length());
4433 result.append("\"\n");
4434 }
4435 result.append("\n");
4436}
4437
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004438void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004439 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4440 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004441 result.appendFormat("DisplayColorSetting: %s\n",
4442 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004443
4444 // TODO: print out if wide-color mode is active or not
4445
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004446 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004447 const int32_t displayId = display->getId();
4448 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004449 continue;
4450 }
4451
Dominik Laskowski7e045462018-05-30 13:02:02 -07004452 result.appendFormat("Display %d color modes:\n", displayId);
4453 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004454 for (auto&& mode : modes) {
4455 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4456 }
4457
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004458 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004459 result.appendFormat(" Current color mode: %s (%d)\n",
4460 decodeColorMode(currentMode).c_str(), currentMode);
4461 }
4462 result.append("\n");
4463}
4464
David Sodman7e4ae112018-02-09 15:02:28 -08004465void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4466 std::string stringResult;
4467
4468 for (const auto& [token, display] : mDisplays) {
4469 const auto displayId = display->getId();
4470 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4471 continue;
4472 }
4473
4474 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4475 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4476 break;
4477 }
4478 const auto& compositionInfoList = compositionInfoIt->second;
4479 stringResult += base::StringPrintf("Display: %d\n", displayId);
4480 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4481 for (const auto& compositionInfo : compositionInfoList) {
4482 compositionInfo.dump(stringResult, nullptr);
4483 stringResult += base::StringPrintf("\n");
4484 }
4485 }
4486
4487 result.append(stringResult.c_str());
4488}
4489
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004490LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004491 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004492 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4493 const State& state = useDrawing ? mDrawingState : mCurrentState;
4494 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004495 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004496 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004497 });
4498
4499 return layersProto;
4500}
4501
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004502LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004503 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004504
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004505 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004506 resolution->set_w(display.getWidth());
4507 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004508
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004509 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4510 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4511 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004512
Dominik Laskowski7e045462018-05-30 13:02:02 -07004513 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004514 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004515 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004516 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004517 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004518 }
4519 });
4520
4521 return layersProto;
4522}
4523
Mathias Agopian74d211a2013-04-22 16:55:35 +02004524void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4525 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004526{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004527 bool colorize = false;
4528 if (index < args.size()
4529 && (args[index] == String16("--color"))) {
4530 colorize = true;
4531 index++;
4532 }
4533
4534 Colorizer colorizer(colorize);
4535
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004536 // figure out if we're stuck somewhere
4537 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004538 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004539 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4540
4541 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004542 * Dump library configuration.
4543 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004544
4545 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004546 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004547 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004548 appendSfConfigString(result);
4549 appendUiConfigString(result);
4550 appendGuiConfigString(result);
4551 result.append("\n");
4552
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004553 result.append("\nDisplay identification data:\n");
4554 dumpDisplayIdentificationData(result);
4555
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004556 result.append("\nWide-Color information:\n");
4557 dumpWideColorInfo(result);
4558
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004559 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004560 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004561 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004562 result.append(SyncFeatures::getInstance().toString());
4563 result.append("\n");
4564
Andy McFadden41d67d72014-04-25 16:58:34 -07004565 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004566 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004567 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004568
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004569 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4570 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004571 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4572 getHwComposer().isConnected(displayId)) {
4573 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004574 result.appendFormat("Display %d: "
4575 "app phase %" PRId64 " ns, "
4576 "sf phase %" PRId64 " ns, "
4577 "early app phase %" PRId64 " ns, "
4578 "early sf phase %" PRId64 " ns, "
4579 "early app gl phase %" PRId64 " ns, "
4580 "early sf gl phase %" PRId64 " ns, "
4581 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4582 displayId,
4583 vsyncPhaseOffsetNs,
4584 sfVsyncPhaseOffsetNs,
4585 appEarlyOffset,
4586 sfEarlyOffset,
4587 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004588 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004589 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004590 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004591 result.append("\n");
4592
Dan Stozab90cf072015-03-05 11:05:59 -08004593 // Dump static screen stats
4594 result.append("\n");
4595 dumpStaticScreenStats(result);
4596 result.append("\n");
4597
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004598 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4599
Dan Stozae77c7662016-05-13 11:37:28 -07004600 dumpBufferingStats(result);
4601
Andy McFadden4803b742012-09-24 19:07:20 -07004602 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004603 * Dump the visible layer list
4604 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004605 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004606 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004607 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4608 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004609 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004610
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004611 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004612 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004613 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004614 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615
David Sodman7e4ae112018-02-09 15:02:28 -08004616 result.append("\nFrame-Composition information:\n");
4617 dumpFrameCompositionInfo(result);
4618 result.append("\n");
4619
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004620 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004621 * Dump Display state
4622 */
4623
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004625 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004626 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004627 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004628 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004629 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004630 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004631
4632 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004633 * Dump SurfaceFlinger global state
4634 */
4635
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004637 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004638 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004639
Mathias Agopian888c8222012-08-04 21:10:38 -07004640 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004641 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004642
David Sodmanbc815282017-11-05 18:57:52 -08004643 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004644
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004645 if (display) {
4646 display->undefinedRegion.dump(result, "undefinedRegion");
4647 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4648 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004649 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004650 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004651 " gpu_to_cpu_unsupported : %d\n",
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004652 mTransactionFlags, !mGpuToCpuSupported);
4653
4654 if (display) {
4655 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4656 result.appendFormat(" refresh-rate : %f fps\n"
4657 " x-dpi : %f\n"
4658 " y-dpi : %f\n",
4659 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4660 activeConfig->getDpiY());
4661 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004662
Mathias Agopian74d211a2013-04-22 16:55:35 +02004663 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004664 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004665
Ana Krulec98b5b242018-08-10 15:03:23 -07004666 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004667 /*
4668 * VSYNC state
4669 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004670 if (mUseScheduler) {
4671 mScheduler->dump(mAppConnectionHandle, result);
4672 } else {
4673 mEventThread->dump(result);
4674 }
Dan Stozae22aec72016-08-01 13:20:59 -07004675 result.append("\n");
4676
4677 /*
4678 * HWC layer minidump
4679 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004680 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004681 const int32_t displayId = display->getId();
4682 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004683 continue;
4684 }
4685
Dominik Laskowski7e045462018-05-30 13:02:02 -07004686 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004687 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004688 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004689 result.append("\n");
4690 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004691
4692 /*
4693 * Dump HWComposer state
4694 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004695 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004696 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004697 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004698 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004699 result.appendFormat(" h/w composer %s\n",
4700 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004701 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004702
4703 /*
4704 * Dump gralloc state
4705 */
4706 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4707 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004708
4709 /*
4710 * Dump VrFlinger state if in use.
4711 */
4712 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4713 result.append("VrFlinger state:\n");
4714 result.append(mVrFlinger->Dump().c_str());
4715 result.append("\n");
4716 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004717}
4718
Dominik Laskowski7e045462018-05-30 13:02:02 -07004719const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004720 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004721 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004722 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004723 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004724 }
4725 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004726
4727 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4728 static const Vector<sp<Layer>> empty;
4729 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004730}
4731
Keun young Park63f165f2012-08-31 10:53:36 -07004732bool SurfaceFlinger::startDdmConnection()
4733{
4734 void* libddmconnection_dso =
4735 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4736 if (!libddmconnection_dso) {
4737 return false;
4738 }
4739 void (*DdmConnection_start)(const char* name);
4740 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004741 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004742 if (!DdmConnection_start) {
4743 dlclose(libddmconnection_dso);
4744 return false;
4745 }
4746 (*DdmConnection_start)(getServiceName());
4747 return true;
4748}
4749
Chia-I Wu28f320b2018-05-03 11:02:56 -07004750void SurfaceFlinger::updateColorMatrixLocked() {
4751 mat4 colorMatrix;
4752 if (mGlobalSaturationFactor != 1.0f) {
4753 // Rec.709 luma coefficients
4754 float3 luminance{0.213f, 0.715f, 0.072f};
4755 luminance *= 1.0f - mGlobalSaturationFactor;
4756 mat4 saturationMatrix = mat4(
4757 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4758 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4759 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4760 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4761 );
4762 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4763 } else {
4764 colorMatrix = mClientColorMatrix * mDaltonizer();
4765 }
4766
4767 if (mCurrentState.colorMatrix != colorMatrix) {
4768 mCurrentState.colorMatrix = colorMatrix;
4769 mCurrentState.colorMatrixChanged = true;
4770 setTransactionFlags(eTransactionNeeded);
4771 }
4772}
4773
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004774status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775#pragma clang diagnostic push
4776#pragma clang diagnostic error "-Wswitch-enum"
4777 switch (static_cast<ISurfaceComposerTag>(code)) {
4778 // These methods should at minimum make sure that the client requested
4779 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004780 case BOOT_FINISHED:
4781 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004782 case CREATE_CONNECTION:
4783 case CREATE_DISPLAY:
4784 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004785 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004786 case GET_ACTIVE_COLOR_MODE:
4787 case GET_ANIMATION_FRAME_STATS:
4788 case GET_HDR_CAPABILITIES:
4789 case SET_ACTIVE_CONFIG:
4790 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004791 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004793 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4794 IPCThreadState* ipc = IPCThreadState::self();
4795 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4796 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004797 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004798 }
Robert Carr1db73f62016-12-21 12:58:51 -08004799 return OK;
4800 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004801 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004802 IPCThreadState* ipc = IPCThreadState::self();
4803 const int pid = ipc->getCallingPid();
4804 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4806 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004807 return PERMISSION_DENIED;
4808 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004809 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004810 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004811 // Used by apps to hook Choreographer to SurfaceFlinger.
4812 case CREATE_DISPLAY_EVENT_CONNECTION:
4813 // The following calls are currently used by clients that do not
4814 // request necessary permissions. However, they do not expose any secret
4815 // information, so it is OK to pass them.
4816 case AUTHENTICATE_SURFACE:
4817 case GET_ACTIVE_CONFIG:
4818 case GET_BUILT_IN_DISPLAY:
4819 case GET_DISPLAY_COLOR_MODES:
4820 case GET_DISPLAY_CONFIGS:
4821 case GET_DISPLAY_STATS:
4822 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4823 // Calling setTransactionState is safe, because you need to have been
4824 // granted a reference to Client* and Handle* to do anything with it.
4825 case SET_TRANSACTION_STATE:
4826 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4827 case CREATE_SCOPED_CONNECTION: {
4828 return OK;
4829 }
4830 case CAPTURE_LAYERS:
4831 case CAPTURE_SCREEN: {
4832 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004833 IPCThreadState* ipc = IPCThreadState::self();
4834 const int pid = ipc->getCallingPid();
4835 const int uid = ipc->getCallingUid();
4836 if ((uid != AID_GRAPHICS) &&
4837 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4838 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4839 return PERMISSION_DENIED;
4840 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841 return OK;
4842 }
4843 // The following codes are deprecated and should never be allowed to access SF.
4844 case CONNECT_DISPLAY_UNUSED:
4845 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4846 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4847 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004848 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004849 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004850
4851 // These codes are used for the IBinder protocol to either interrogate the recipient
4852 // side of the transaction for its canonical interface descriptor or to dump its state.
4853 // We let them pass by default.
4854 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4855 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4856 code == IBinder::SYSPROPS_TRANSACTION) {
4857 return OK;
4858 }
4859 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4860 // in onTransact verifies that the user is root, and has access to use SF.
4861 if (code >= 1000 && code <= 1029) {
4862 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4863 return OK;
4864 }
4865 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4866 return PERMISSION_DENIED;
4867#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004868}
4869
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4871 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004872 status_t credentialCheck = CheckTransactCodeCredentials(code);
4873 if (credentialCheck != OK) {
4874 return credentialCheck;
4875 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004876
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004877 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4878 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004879 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004880 IPCThreadState* ipc = IPCThreadState::self();
4881 const int uid = ipc->getCallingUid();
4882 if (CC_UNLIKELY(uid != AID_SYSTEM
4883 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004884 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004885 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004886 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004887 return PERMISSION_DENIED;
4888 }
4889 int n;
4890 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004891 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004892 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 return NO_ERROR;
4894 case 1002: // SHOW_UPDATES
4895 n = data.readInt32();
4896 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004897 invalidateHwcGeometry();
4898 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004899 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004900 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004901 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004902 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004903 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004904 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004905 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004906 setTransactionFlags(
4907 eTransactionNeeded|
4908 eDisplayTransactionNeeded|
4909 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004910 return NO_ERROR;
4911 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004912 case 1006:{ // send empty update
4913 signalRefresh();
4914 return NO_ERROR;
4915 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004916 case 1008: // toggle use of hw composer
4917 n = data.readInt32();
4918 mDebugDisableHWC = n ? 1 : 0;
4919 invalidateHwcGeometry();
4920 repaintEverything();
4921 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004922 case 1009: // toggle use of transform hint
4923 n = data.readInt32();
4924 mDebugDisableTransformHint = n ? 1 : 0;
4925 invalidateHwcGeometry();
4926 repaintEverything();
4927 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004929 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004930 reply->writeInt32(0);
4931 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004932 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004933 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004934 return NO_ERROR;
4935 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004936 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004937 if (!display) {
4938 return NAME_NOT_FOUND;
4939 }
4940
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004941 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004942 return NO_ERROR;
4943 }
4944 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004945 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004946 // daltonize
4947 n = data.readInt32();
4948 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004949 case 1:
4950 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4951 break;
4952 case 2:
4953 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4954 break;
4955 case 3:
4956 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4957 break;
4958 default:
4959 mDaltonizer.setType(ColorBlindnessType::None);
4960 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004961 }
4962 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004963 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004964 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004965 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004966 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004967
4968 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004971 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004972 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004973 // apply a color matrix
4974 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004975 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004976 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004977 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004978 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004979 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004980 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004981 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004982 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004983 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004984 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004985
4986 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4987 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004988 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004989 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4990 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4991 }
4992
Chia-I Wu28f320b2018-05-03 11:02:56 -07004993 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004994 return NO_ERROR;
4995 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004996 // This is an experimental interface
4997 // Needs to be shifted to proper binder interface when we productize
4998 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004999 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005000 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005001 return NO_ERROR;
5002 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005003 case 1017: {
5004 n = data.readInt32();
5005 mForceFullDamage = static_cast<bool>(n);
5006 return NO_ERROR;
5007 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005008 case 1018: { // Modify Choreographer's phase offset
5009 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005010 if (mUseScheduler) {
5011 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5012 } else {
5013 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5014 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005015 return NO_ERROR;
5016 }
5017 case 1019: { // Modify SurfaceFlinger's phase offset
5018 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005019 if (mUseScheduler) {
5020 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5021 } else {
5022 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5023 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005024 return NO_ERROR;
5025 }
Irvel468051e2016-06-13 16:44:44 -07005026 case 1020: { // Layer updates interceptor
5027 n = data.readInt32();
5028 if (n) {
5029 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005030 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005031 }
5032 else{
5033 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005034 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005035 }
5036 return NO_ERROR;
5037 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005038 case 1021: { // Disable HWC virtual displays
5039 n = data.readInt32();
5040 mUseHwcVirtualDisplays = !n;
5041 return NO_ERROR;
5042 }
Romain Guy0147a172017-06-01 13:53:56 -07005043 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005044 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005045 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005046
Chia-I Wu28f320b2018-05-03 11:02:56 -07005047 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005048 return NO_ERROR;
5049 }
Romain Guy54f154a2017-10-24 21:40:32 +01005050 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005051 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005052 invalidateHwcGeometry();
5053 repaintEverything();
5054 return NO_ERROR;
5055 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005056 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5057 // deprecate 1024 if they can.
5058 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005059 reply->writeBool(hasWideColorDisplay);
5060 return NO_ERROR;
5061 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005062 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005063 n = data.readInt32();
5064 if (n) {
5065 ALOGV("LayerTracing enabled");
5066 mTracing.enable();
5067 doTracing("tracing.enable");
5068 reply->writeInt32(NO_ERROR);
5069 } else {
5070 ALOGV("LayerTracing disabled");
5071 status_t err = mTracing.disable();
5072 reply->writeInt32(err);
5073 }
5074 return NO_ERROR;
5075 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005076 case 1026: { // Get layer tracing status
5077 reply->writeBool(mTracing.isEnabled());
5078 return NO_ERROR;
5079 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005080 // Is a DisplayColorSetting supported?
5081 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005082 const auto display = getDefaultDisplayDevice();
5083 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005084 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005085 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005086
5087 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5088 switch (setting) {
5089 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005090 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005091 break;
5092 case DisplayColorSetting::UNMANAGED:
5093 reply->writeBool(true);
5094 break;
5095 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005096 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005097 break;
5098 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005099 reply->writeBool(
5100 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005101 break;
5102 }
5103 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005104 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005105 // Is VrFlinger active?
5106 case 1028: {
5107 Mutex::Autolock _l(mStateLock);
5108 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5109 return NO_ERROR;
5110 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005111 case 1029: {
5112 // Code 1029 is an experimental feature that allows applications to
5113 // simulate a high frequency panel by setting a multiplier and divisor
5114 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005115 // 0, then the code simply return the current multiplier and divisor.
5116 HWC2::Device::FrequencyScaler frequencyScaler;
5117 frequencyScaler.multiplier = data.readInt32();
5118 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005119
David Sodman44b5de02018-08-21 16:28:53 -07005120 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5121 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5122 reply->writeInt32(frequencyScaler.multiplier);
5123 reply->writeInt32(frequencyScaler.divisor);
5124 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005125 }
5126
David Sodman44b5de02018-08-21 16:28:53 -07005127 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005128 enableHardwareVsync();
5129 } else {
5130 disableHardwareVsync(true);
5131 }
David Sodman44b5de02018-08-21 16:28:53 -07005132 mPrimaryDispSync->scalePeriod(frequencyScaler);
5133 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005134
David Sodman44b5de02018-08-21 16:28:53 -07005135 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5136 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5137
5138 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5139 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5140
5141 onHotplugReceived(getBE().mComposerSequenceId,
5142 hwcDisplayId, HWC2::Connection::Disconnected);
5143 onHotplugReceived(getBE().mComposerSequenceId,
5144 hwcDisplayId, HWC2::Connection::Connected);
5145 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5146 reply->writeInt32(frequencyScaler.multiplier);
5147 reply->writeInt32(frequencyScaler.divisor);
5148
David Sodman6d46c1e2018-07-13 12:59:48 -07005149 return NO_ERROR;
5150 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005151 // Is device color managed?
5152 case 1030: {
5153 reply->writeBool(useColorManagement);
5154 return NO_ERROR;
5155 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005156 }
5157 }
5158 return err;
5159}
5160
Steven Thomas6d8110b2017-08-31 18:24:21 -07005161void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07005162 android_atomic_or(1, &mRepaintEverything);
5163 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005164}
5165
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005166// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5167class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005168public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005169 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5170 ~WindowDisconnector() {
5171 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005172 }
5173
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005174private:
5175 ANativeWindow* mWindow;
5176 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005177};
5178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005179status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5180 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
5181 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
5182 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005183 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005184 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005186 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005187
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005188 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5189
Chia-I Wu20261cb2018-08-23 12:55:44 -07005190 sp<DisplayDevice> display;
5191 {
5192 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005193
Chia-I Wu20261cb2018-08-23 12:55:44 -07005194 display = getDisplayDeviceLocked(displayToken);
5195 if (!display) return BAD_VALUE;
5196
Chia-I Wu8730ba82018-08-29 09:25:59 -07005197 // ignore sourceCrop (i.e., use the projected logical display
5198 // viewport) until the framework is fixed
5199 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005200
5201 // set the requested width/height to the logical display viewport size
5202 // by default
5203 if (reqWidth == 0 || reqHeight == 0) {
5204 reqWidth = uint32_t(display->getViewport().width());
5205 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005206 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005207 }
5208
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005209 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005210
5211 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005212 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005213 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005214}
5215
5216status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005217 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005218 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005219 ATRACE_CALL();
5220
5221 class LayerRenderArea : public RenderArea {
5222 public:
Robert Carr578038f2018-03-09 12:25:24 -08005223 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5224 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005225 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005226 mLayer(layer),
5227 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005228 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005229 mFlinger(flinger),
5230 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005231 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005232 Rect getBounds() const override {
5233 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005234 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005235 }
Marissa Wall61c58622018-07-18 10:12:20 -07005236 int getHeight() const override {
5237 return mLayer->getActiveHeight(mLayer->getDrawingState());
5238 }
5239 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005240 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005241 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005242 Rect getSourceCrop() const override {
5243 if (mCrop.isEmpty()) {
5244 return getBounds();
5245 } else {
5246 return mCrop;
5247 }
5248 }
Robert Carr578038f2018-03-09 12:25:24 -08005249 class ReparentForDrawing {
5250 public:
5251 const sp<Layer>& oldParent;
5252 const sp<Layer>& newParent;
5253
5254 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5255 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005256 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005257 }
Robert Carr15eae092018-03-23 13:43:53 -07005258 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005259 };
5260
5261 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005262 const Rect sourceCrop = getSourceCrop();
5263 // no need to check rotation because there is none
5264 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5265 sourceCrop.height() != getReqHeight();
5266
Robert Carr578038f2018-03-09 12:25:24 -08005267 if (!mChildrenOnly) {
5268 mTransform = mLayer->getTransform().inverse();
5269 drawLayers();
5270 } else {
5271 Rect bounds = getBounds();
5272 screenshotParentLayer =
5273 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5274 bounds.getWidth(), bounds.getHeight(), 0);
5275
5276 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5277 drawLayers();
5278 }
5279 }
chaviwa76b2712017-09-20 12:02:26 -07005280
chaviwa76b2712017-09-20 12:02:26 -07005281 private:
chaviw7206d492017-11-10 16:16:12 -08005282 const sp<Layer> mLayer;
5283 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005284
5285 // In the "childrenOnly" case we reparent the children to a screenshot
5286 // layer which has no properties set and which does not draw.
5287 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005288 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005289 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005290
5291 SurfaceFlinger* mFlinger;
5292 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005293 };
5294
5295 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5296 auto parent = layerHandle->owner.promote();
5297
chaviw7206d492017-11-10 16:16:12 -08005298 if (parent == nullptr || parent->isPendingRemoval()) {
5299 ALOGE("captureLayers called with a removed parent");
5300 return NAME_NOT_FOUND;
5301 }
5302
Robert Carr578038f2018-03-09 12:25:24 -08005303 const int uid = IPCThreadState::self()->getCallingUid();
5304 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5305 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5306 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5307 return PERMISSION_DENIED;
5308 }
5309
chaviw7206d492017-11-10 16:16:12 -08005310 Rect crop(sourceCrop);
5311 if (sourceCrop.width() <= 0) {
5312 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005313 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005314 }
5315
5316 if (sourceCrop.height() <= 0) {
5317 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005318 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005319 }
5320
5321 int32_t reqWidth = crop.width() * frameScale;
5322 int32_t reqHeight = crop.height() * frameScale;
5323
Chia-I Wu20261cb2018-08-23 12:55:44 -07005324 // really small crop or frameScale
5325 if (reqWidth <= 0) {
5326 reqWidth = 1;
5327 }
5328 if (reqHeight <= 0) {
5329 reqHeight = 1;
5330 }
5331
Robert Carr578038f2018-03-09 12:25:24 -08005332 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005333
Robert Carr578038f2018-03-09 12:25:24 -08005334 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005335 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5336 if (!layer->isVisible()) {
5337 return;
Robert Carr578038f2018-03-09 12:25:24 -08005338 } else if (childrenOnly && layer == parent.get()) {
5339 return;
chaviwa76b2712017-09-20 12:02:26 -07005340 }
5341 visitor(layer);
5342 });
5343 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005344 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005345}
5346
5347status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5348 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005349 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005350 bool useIdentityTransform) {
5351 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005352
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005353 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5354 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5355 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5356 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357
5358 // This mutex protects syncFd and captureResult for communication of the return values from the
5359 // main thread back to this Binder thread
5360 std::mutex captureMutex;
5361 std::condition_variable captureCondition;
5362 std::unique_lock<std::mutex> captureLock(captureMutex);
5363 int syncFd = -1;
5364 std::optional<status_t> captureResult;
5365
Robert Carr03480e22018-01-04 16:02:06 -08005366 const int uid = IPCThreadState::self()->getCallingUid();
5367 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5368
Dominik Laskowski8c001672018-05-30 16:52:06 -07005369 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005370 // If there is a refresh pending, bug out early and tell the binder thread to try again
5371 // after the refresh.
5372 if (mRefreshPending) {
5373 ATRACE_NAME("Skipping screenshot for now");
5374 std::unique_lock<std::mutex> captureLock(captureMutex);
5375 captureResult = std::make_optional<status_t>(EAGAIN);
5376 captureCondition.notify_one();
5377 return;
5378 }
5379
5380 status_t result = NO_ERROR;
5381 int fd = -1;
5382 {
5383 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005384 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005385 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5386 useIdentityTransform, forSystem, &fd);
5387 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388 }
5389
5390 {
5391 std::unique_lock<std::mutex> captureLock(captureMutex);
5392 syncFd = fd;
5393 captureResult = std::make_optional<status_t>(result);
5394 captureCondition.notify_one();
5395 }
5396 });
5397
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005398 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005399 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005400 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005401 while (*captureResult == EAGAIN) {
5402 captureResult.reset();
5403 result = postMessageAsync(message);
5404 if (result != NO_ERROR) {
5405 return result;
5406 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005407 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005408 }
5409 result = *captureResult;
5410 }
5411
5412 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005413 sync_wait(syncFd, -1);
5414 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005415 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005416
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005417 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005418}
5419
chaviwa76b2712017-09-20 12:02:26 -07005420void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005421 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005422 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005423 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005424
Lloyd Pique144e1162017-12-20 16:44:52 -08005425 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005426
chaviwa76b2712017-09-20 12:02:26 -07005427 const auto reqWidth = renderArea.getReqWidth();
5428 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005429 const auto sourceCrop = renderArea.getSourceCrop();
5430 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005431
Chia-I Wu36574d92018-05-16 10:54:36 -07005432 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5433 engine.setOutputDataSpace(Dataspace::SRGB);
5434 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005435
Mathias Agopian180f10d2013-04-10 22:55:41 -07005436 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005437 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005438
5439 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005440 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005441 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005442
chaviw50da5042018-04-09 13:49:37 -07005443 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005444 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005445 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005446
chaviwa76b2712017-09-20 12:02:26 -07005447 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005448 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005449 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005450}
5451
chaviwa76b2712017-09-20 12:02:26 -07005452status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5453 TraverseLayersFunction traverseLayers,
5454 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005455 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005456 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005457 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005458 ATRACE_CALL();
5459
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005460 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005461
5462 traverseLayers([&](Layer* layer) {
5463 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5464 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005465
Robert Carr03480e22018-01-04 16:02:06 -08005466 // We allow the system server to take screenshots of secure layers for
5467 // use in situations like the Screen-rotation animation and place
5468 // the impetus on WindowManager to not persist them.
5469 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005470 ALOGW("FB is protected: PERMISSION_DENIED");
5471 return PERMISSION_DENIED;
5472 }
5473
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005474 // this binds the given EGLImage as a framebuffer for the
5475 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005476 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005477 if (bufferBond.getStatus() != NO_ERROR) {
5478 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005479 return INVALID_OPERATION;
5480 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005481
Dan Stozaabcda352017-06-01 14:37:39 -07005482 // this will in fact render into our dequeued buffer
5483 // via an FBO, which means we didn't have to create
5484 // an EGLSurface and therefore we're not
5485 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005486 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005487
Dan Stozaabcda352017-06-01 14:37:39 -07005488 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005489 getRenderEngine().finish();
5490 *outSyncFd = -1;
5491
chaviwa76b2712017-09-20 12:02:26 -07005492 const auto reqWidth = renderArea.getReqWidth();
5493 const auto reqHeight = renderArea.getReqHeight();
5494
Dan Stozaabcda352017-06-01 14:37:39 -07005495 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5496 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005497 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005498 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005499 } else {
5500 base::unique_fd syncFd = getRenderEngine().flush();
5501 if (syncFd < 0) {
5502 getRenderEngine().finish();
5503 }
5504 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005505 }
5506
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005507 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005508}
5509
Mathias Agopiand5556842013-09-19 17:08:37 -07005510void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005511 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005512 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005513 for (size_t y = 0; y < h; y++) {
5514 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5515 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005516 if (p[x] != 0xFF000000) return;
5517 }
5518 }
chaviwa76b2712017-09-20 12:02:26 -07005519 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005520
Robert Carr2047fae2016-11-28 14:09:09 -08005521 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005522 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005523 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005524 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5525 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5526 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5527 static_cast<float>(state.color.a));
5528 i++;
5529 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005530 }
5531}
5532
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005533// ---------------------------------------------------------------------------
5534
Dan Stoza412903f2017-04-27 13:42:17 -07005535void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5536 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005537}
5538
Dan Stoza412903f2017-04-27 13:42:17 -07005539void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5540 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005541}
5542
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005543void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5544 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005545 const LayerVector::Visitor& visitor) {
5546 // We loop through the first level of layers without traversing,
5547 // as we need to interpret min/max layer Z in the top level Z space.
5548 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005549 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005550 continue;
5551 }
5552 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005553 // relative layers are traversed in Layer::traverseInZOrder
5554 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005555 continue;
5556 }
5557 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005558 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005559 return;
5560 }
chaviwa76b2712017-09-20 12:02:26 -07005561 if (!layer->isVisible()) {
5562 return;
5563 }
5564 visitor(layer);
5565 });
5566 }
5567}
5568
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005569}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005570
Lloyd Pique074e8122018-07-26 12:57:23 -07005571
Mathias Agopian3f844832013-08-07 21:24:32 -07005572#if defined(__gl_h_)
5573#error "don't include gl/gl.h in this file"
5574#endif
5575
5576#if defined(__gl2_h_)
5577#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005578#endif