blob: b2d26de14ef0645c0eabf25cda864d3b9ebe1831 [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
106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jaesoo Lee43518572017-01-23 19:03:16 +0900108using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900109using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700110using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700111using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700112using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700113using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114
Steven Thomasb02664d2017-07-26 18:48:28 -0700115namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700116
117#pragma clang diagnostic push
118#pragma clang diagnostic error "-Wswitch-enum"
119
120bool isWideColorMode(const ColorMode colorMode) {
121 switch (colorMode) {
122 case ColorMode::DISPLAY_P3:
123 case ColorMode::ADOBE_RGB:
124 case ColorMode::DCI_P3:
125 case ColorMode::BT2020:
126 case ColorMode::BT2100_PQ:
127 case ColorMode::BT2100_HLG:
128 return true;
129 case ColorMode::NATIVE:
130 case ColorMode::STANDARD_BT601_625:
131 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
132 case ColorMode::STANDARD_BT601_525:
133 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
134 case ColorMode::STANDARD_BT709:
135 case ColorMode::SRGB:
136 return false;
137 }
138 return false;
139}
140
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700141ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
142 switch (rotation) {
143 case ISurfaceComposer::eRotateNone:
144 return ui::Transform::ROT_0;
145 case ISurfaceComposer::eRotate90:
146 return ui::Transform::ROT_90;
147 case ISurfaceComposer::eRotate180:
148 return ui::Transform::ROT_180;
149 case ISurfaceComposer::eRotate270:
150 return ui::Transform::ROT_270;
151 }
152 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
153 return ui::Transform::ROT_0;
154}
155
Peiyong Linfca547f2018-07-09 13:03:33 -0700156#pragma clang diagnostic pop
157
Steven Thomasb02664d2017-07-26 18:48:28 -0700158class ConditionalLock {
159public:
160 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
161 if (lock) {
162 mMutex.lock();
163 }
164 }
165 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
166private:
167 Mutex& mMutex;
168 bool mLocked;
169};
Peiyong Linfca547f2018-07-09 13:03:33 -0700170
Steven Thomasb02664d2017-07-26 18:48:28 -0700171} // namespace anonymous
172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173// ---------------------------------------------------------------------------
174
Mathias Agopian99b49842011-06-27 16:05:52 -0700175const String16 sHardwareTest("android.permission.HARDWARE_TEST");
176const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
177const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
178const String16 sDump("android.permission.DUMP");
179
180// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800181int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
182int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700183int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700184bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800185uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800186bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800187bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800188int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800189// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600190bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700191int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700192bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700193bool SurfaceFlinger::useContextPriority;
Peiyong Lin0256f722018-08-31 15:45:10 -0700194Dataspace SurfaceFlinger::compositionDataSpace = Dataspace::V0_SRGB;
195ui::PixelFormat SurfaceFlinger::compositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700196
Kalle Raitaa099a242017-01-11 11:17:29 -0800197std::string getHwcServiceName() {
198 char value[PROPERTY_VALUE_MAX] = {};
199 property_get("debug.sf.hwc_service_name", value, "default");
200 ALOGI("Using HWComposer service: '%s'", value);
201 return std::string(value);
202}
203
204bool useTrebleTestingOverride() {
205 char value[PROPERTY_VALUE_MAX] = {};
206 property_get("debug.sf.treble_testing_override", value, "false");
207 ALOGI("Treble testing override: '%s'", value);
208 return std::string(value) == "true";
209}
210
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800211std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
212 switch(displayColorSetting) {
213 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700214 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800215 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700216 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800217 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700218 return std::string("Enhanced");
219 default:
220 return std::string("Unknown ") +
221 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800223}
224
Lloyd Pique99d3da52018-01-22 17:48:03 -0800225NativeWindowSurface::~NativeWindowSurface() = default;
226
227namespace impl {
228
229class NativeWindowSurface final : public android::NativeWindowSurface {
230public:
231 static std::unique_ptr<android::NativeWindowSurface> create(
232 const sp<IGraphicBufferProducer>& producer) {
233 return std::make_unique<NativeWindowSurface>(producer);
234 }
235
236 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
237 : surface(new Surface(producer, false)) {}
238
239 ~NativeWindowSurface() override = default;
240
241private:
242 sp<ANativeWindow> getNativeWindow() const override { return surface; }
243
244 void preallocateBuffers() override { surface->allocateBuffers(); }
245
246 sp<Surface> surface;
247};
248
249} // namespace impl
250
David Sodmanbc815282017-11-05 18:57:52 -0800251SurfaceFlingerBE::SurfaceFlingerBE()
252 : mHwcServiceName(getHwcServiceName()),
253 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800254 mFrameBuckets(),
255 mTotalTime(0),
256 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800257 mComposerSequenceId(0) {
258}
259
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800260SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800261 : BnSurfaceComposer(),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700262 mTransactionPending(false),
263 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700264 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700265 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800266 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700267 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800269 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800270 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800271 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800272 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700273 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700274 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700275 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700276 mDebugInTransaction(0),
277 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700278 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700279 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700280 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800281 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800282 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700284 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800285 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800286 mCreateBufferQueue(&BufferQueue::createBufferQueue),
287 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800288
289SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800290 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800291
292 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
293 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
294
295 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
296 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
297
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800298 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800300
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700301 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
303
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700304 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
305 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
306
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800307 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
308 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
309
Steven Thomas050b2c82017-03-06 11:45:16 -0800310 // Vr flinger is only enabled on Daydream ready devices.
311 useVrFlinger = getBool< ISurfaceFlingerConfigs,
312 &ISurfaceFlingerConfigs::useVrFlinger>(false);
313
Fabien Sanglard1971b632017-03-10 14:50:03 -0800314 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
315 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
316
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600317 hasWideColorDisplay =
318 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700319 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700320 getBool<V1_2::ISurfaceFlingerConfigs,
321 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
322
323 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
324 if (surfaceFlingerConfigsServiceV1_2) {
325 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
326 [&](Dataspace tmpDataSpace, ui::PixelFormat tmpPixelFormat) {
327 compositionDataSpace = tmpDataSpace;
328 compositionPixelFormat = tmpPixelFormat;
329 });
330 }
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600331
Peiyong Linb3839ad2018-09-05 15:37:19 -0700332 useContextPriority = getBool<ISurfaceFlingerConfigs,
333 &ISurfaceFlingerConfigs::useContextPriority>(true);
334
Iris Chang7501ed62018-04-30 14:45:42 +0800335 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700336 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
337 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800338 V1_1::DisplayOrientation::ORIENTATION_0);
339
340 switch (primaryDisplayOrientation) {
341 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800346 break;
347 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700348 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800349 break;
350 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700351 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800352 break;
353 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700354 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800355
Lloyd Pique41be5d22018-06-21 13:11:48 -0700356 // Note: We create a local temporary with the real DispSync implementation
357 // type temporarily so we can initialize it with the configured values,
358 // before storing it for more generic use using the interface type.
359 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
360 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
361 SurfaceFlinger::dispSyncPresentTimeOffset);
362 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700363
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800364 // debugging stuff...
365 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700366
Mathias Agopianb4b17302013-03-20 18:36:41 -0700367 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700368 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700369
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800370 property_get("debug.sf.showupdates", value, "0");
371 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700372
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700373 property_get("debug.sf.ddms", value, "0");
374 mDebugDDMS = atoi(value);
375 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700376 if (!startDdmConnection()) {
377 // start failed, and DDMS debugging not enabled
378 mDebugDDMS = 0;
379 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700380 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700381 ALOGI_IF(mDebugRegion, "showupdates enabled");
382 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700383
384 property_get("debug.sf.disable_backpressure", value, "0");
385 mPropagateBackpressure = !atoi(value);
386 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700387
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800388 property_get("debug.sf.enable_hwc_vds", value, "0");
389 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800390 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800391
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800392 property_get("ro.sf.disable_triple_buffer", value, "1");
393 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800394 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700395
Yiwei Zhang243b3782018-05-15 17:40:04 -0700396 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700397 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
398 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
399
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200400 property_get("debug.sf.early_phase_offset_ns", value, "-1");
401 const int earlySfOffsetNs = atoi(value);
402
403 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
404 const int earlyGlSfOffsetNs = atoi(value);
405
406 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
407 const int earlyAppOffsetNs = atoi(value);
408
409 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
410 const int earlyGlAppOffsetNs = atoi(value);
411
Ana Krulec98b5b242018-08-10 15:03:23 -0700412 property_get("debug.sf.use_scheduler", value, "0");
413 mUseScheduler = atoi(value);
414
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200415 const VSyncModulator::Offsets earlyOffsets =
416 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
417 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
418 const VSyncModulator::Offsets earlyGlOffsets =
419 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
420 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
421 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
422 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700423
Romain Guy11d63f42017-07-20 12:47:14 -0700424 // We should be reading 'persist.sys.sf.color_saturation' here
425 // but since /data may be encrypted, we need to wait until after vold
426 // comes online to attempt to read the property. The property is
427 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800428
429 if (useTrebleTestingOverride()) {
430 // Without the override SurfaceFlinger cannot connect to HIDL
431 // services that are not listed in the manifests. Considered
432 // deriving the setting from the set service name, but it
433 // would be brittle if the name that's not 'default' is used
434 // for production purposes later on.
435 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
436 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800437}
438
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800439void SurfaceFlinger::onFirstRef()
440{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800441 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442}
443
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800444SurfaceFlinger::~SurfaceFlinger()
445{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800446}
447
Dan Stozac7014012014-02-14 15:03:43 -0800448void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800449{
450 // the window manager died on us. prepare its eulogy.
451
Andy McFadden13a082e2012-08-24 10:16:42 -0700452 // restore initial conditions (default device unblank, etc)
453 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800454
455 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700456 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800457}
458
Robert Carr1db73f62016-12-21 12:58:51 -0800459static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700460 status_t err = client->initCheck();
461 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800462 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800463 }
Robert Carr1db73f62016-12-21 12:58:51 -0800464 return nullptr;
465}
466
467sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
468 return initClient(new Client(this));
469}
470
471sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
472 const sp<IGraphicBufferProducer>& gbp) {
473 if (authenticateSurfaceTexture(gbp) == false) {
474 return nullptr;
475 }
476 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
477 if (layer == nullptr) {
478 return nullptr;
479 }
480
481 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800482}
483
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700484sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
485 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700486{
487 class DisplayToken : public BBinder {
488 sp<SurfaceFlinger> flinger;
489 virtual ~DisplayToken() {
490 // no more references, this display must be terminated
491 Mutex::Autolock _l(flinger->mStateLock);
492 flinger->mCurrentState.displays.removeItem(this);
493 flinger->setTransactionFlags(eDisplayTransactionNeeded);
494 }
495 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700496 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 : flinger(flinger) {
498 }
499 };
500
501 sp<BBinder> token = new DisplayToken(this);
502
503 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700504 DisplayDeviceState info;
505 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700506 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700507 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700508 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800509 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510 return token;
511}
512
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700513void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700514 Mutex::Autolock _l(mStateLock);
515
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700516 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700517 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700518 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700519 return;
520 }
521
522 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700523 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700524 ALOGE("destroyDisplay called for non-virtual display");
525 return;
526 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700527 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700528 mCurrentState.displays.removeItemsAt(idx);
529 setTransactionFlags(eDisplayTransactionNeeded);
530}
531
Mathias Agopiane57f2922012-08-09 16:29:12 -0700532sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700533 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700534 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800535 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700536 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700537 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700538}
539
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540void SurfaceFlinger::bootFinished()
541{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700542 if (mStartPropertySetThread->join() != NO_ERROR) {
543 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800544 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800545 const nsecs_t now = systemTime();
546 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000547 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700548
549 // wait patiently for the window manager death
550 const String16 name("window");
551 sp<IBinder> window(defaultServiceManager()->getService(name));
552 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700553 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554 }
555
Steven Thomas050b2c82017-03-06 11:45:16 -0800556 if (mVrFlinger) {
557 mVrFlinger->OnBootFinished();
558 }
559
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700560 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700561 // formerly we would just kill the process, but we now ask it to exit so it
562 // can choose where to stop the animation.
563 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700564
565 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
566 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
567 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700568
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800569 postMessageAsync(new LambdaMessage([this] {
570 readPersistentProperties();
571 mBootStage = BootStage::FINISHED;
572 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800573}
574
Dan Stoza436ccf32018-06-21 12:10:12 -0700575uint32_t SurfaceFlinger::getNewTexture() {
576 {
577 std::lock_guard lock(mTexturePoolMutex);
578 if (!mTexturePool.empty()) {
579 uint32_t name = mTexturePool.back();
580 mTexturePool.pop_back();
581 ATRACE_INT("TexturePoolSize", mTexturePool.size());
582 return name;
583 }
584
585 // The pool was too small, so increase it for the future
586 ++mTexturePoolSize;
587 }
588
589 // The pool was empty, so we need to get a new texture name directly using a
590 // blocking call to the main thread
591 uint32_t name = 0;
592 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
593 return name;
594}
595
Mathias Agopian3f844832013-08-07 21:24:32 -0700596void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700597 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700598}
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
605
Thierry Strudel2924d012017-08-14 15:19:37 -0700606 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900607
Steven Thomasb02664d2017-07-26 18:48:28 -0700608 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800609
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700611 if (mUseScheduler) {
612 mScheduler = std::make_unique<Scheduler>();
613 mAppConnectionHandle =
614 mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
615 SurfaceFlinger::vsyncPhaseOffsetNs,
616 [this] { resyncWithRateLimit(); },
617 impl::EventThread::InterceptVSyncsCallback());
618 mSfConnectionHandle =
619 mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
620 SurfaceFlinger::sfVsyncPhaseOffsetNs,
621 [this] { resyncWithRateLimit(); },
622 [this](nsecs_t timestamp) {
623 mInterceptor->saveVSyncEvent(timestamp);
624 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800625
Ana Krulec98b5b242018-08-10 15:03:23 -0700626 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700627 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
628 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700629 } else {
630 mEventThreadSource =
631 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
632 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
633 mEventThread =
634 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
635 [this] { resyncWithRateLimit(); },
636 impl::EventThread::InterceptVSyncsCallback(),
637 "appEventThread");
638 mSfEventThreadSource =
639 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
640 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
641
642 mSFEventThread =
643 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
644 [this] { resyncWithRateLimit(); },
645 [this](nsecs_t timestamp) {
646 mInterceptor->saveVSyncEvent(timestamp);
647 },
648 "sfEventThread");
649 mEventQueue->setEventThread(mSFEventThread.get());
650 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
651 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800652
Steven Thomasb02664d2017-07-26 18:48:28 -0700653 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700654 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700655 renderEngineFeature |= (useColorManagement ?
656 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700657 renderEngineFeature |= (useContextPriority ?
658 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700659
660 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
661 getBE().mRenderEngine =
Peiyong Linf11f39b2018-09-05 14:37:41 -0700662 renderengine::RenderEngine::create(static_cast<int32_t>(compositionPixelFormat),
663 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800664 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700665
666 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
667 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800668 getBE().mHwc.reset(
669 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700670 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800671 // Process any initial hotplug and resulting display changes.
672 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700673 const auto display = getDefaultDisplayDeviceLocked();
674 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
675 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
676 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800677
Lloyd Piquefcd86612017-12-14 17:15:36 -0800678 // make the default display GLContext current so that we can create textures
679 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700680 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800681
Steven Thomas050b2c82017-03-06 11:45:16 -0800682 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700683 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700684 // This callback is called from the vr flinger dispatch thread. We
685 // need to call signalTransaction(), which requires holding
686 // mStateLock when we're not on the main thread. Acquiring
687 // mStateLock from the vr flinger dispatch thread might trigger a
688 // deadlock in surface flinger (see b/66916578), so post a message
689 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700690 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700691 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
692 mVrFlingerRequestsDisplay = requestDisplay;
693 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700694 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
697 getHwComposer()
698 .getHwcDisplayId(display->getId())
699 .value_or(0),
700 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 if (!mVrFlinger) {
702 ALOGE("Failed to start vrflinger");
703 }
704 }
705
Lloyd Pique379adc12018-01-22 17:31:47 -0800706 mEventControlThread = std::make_unique<impl::EventControlThread>(
707 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700708
Mathias Agopian92a979a2012-08-02 18:32:23 -0700709 // initialize our drawing state
710 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700711
Andy McFadden13a082e2012-08-24 10:16:42 -0700712 // set initial conditions (e.g. unblank default device)
713 initializeDisplays();
714
David Sodmanbc815282017-11-05 18:57:52 -0800715 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700716
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 // Inform native graphics APIs whether the present timestamp is supported:
718 if (getHwComposer().hasCapability(
719 HWC2::Capability::PresentFenceIsNotReliable)) {
720 mStartPropertySetThread = new StartPropertySetThread(false);
721 } else {
722 mStartPropertySetThread = new StartPropertySetThread(true);
723 }
724
725 if (mStartPropertySetThread->Start() != NO_ERROR) {
726 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800727 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800728
Chia-I Wud49d6692018-06-27 07:17:41 +0800729 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
730 // is used to saturate legacy sRGB content. However, to make sure the same color under
731 // Display P3 will be saturated to the same color, we intentionally break the API spec
732 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
733 // such saturation matrix on Display P3 is understood fully, the API should always return
734 // identify matrix.
735 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
736 Dataspace::SRGB_LINEAR);
737
738 // we will apply this on Display P3.
739 if (mEnhancedSaturationMatrix != mat4()) {
740 ColorSpace srgb(ColorSpace::sRGB());
741 ColorSpace displayP3(ColorSpace::DisplayP3());
742 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
743 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
744 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
745 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746
Dan Stoza9e56aa02015-11-02 13:00:03 -0800747 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700748}
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700751 Mutex::Autolock _l(mStateLock);
752
Romain Guy11d63f42017-07-20 12:47:14 -0700753 char value[PROPERTY_VALUE_MAX];
754
755 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800756 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700757 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100759
760 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700761 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700762}
763
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Start boot animation service by setting a property mailbox
766 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800768 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 if (mStartPropertySetThread->join() != NO_ERROR) {
770 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800775 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800779 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800783
Jamie Gennis582270d2011-08-17 18:19:00 -0700784bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800786 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800787 return authenticateSurfaceTextureLocked(bufferProducer);
788}
789
790bool SurfaceFlinger::authenticateSurfaceTextureLocked(
791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800792 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800793 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800794}
795
Brian Anderson6b376712017-04-04 10:51:39 -0700796status_t SurfaceFlinger::getSupportedFrameTimestamps(
797 std::vector<FrameEvent>* outSupported) const {
798 *outSupported = {
799 FrameEvent::REQUESTED_PRESENT,
800 FrameEvent::ACQUIRE,
801 FrameEvent::LATCH,
802 FrameEvent::FIRST_REFRESH_START,
803 FrameEvent::LAST_REFRESH_START,
804 FrameEvent::GPU_COMPOSITION_DONE,
805 FrameEvent::DEQUEUE_READY,
806 FrameEvent::RELEASE,
807 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 ConditionalLock _l(mStateLock,
809 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700810 if (!getHwComposer().hasCapability(
811 HWC2::Capability::PresentFenceIsNotReliable)) {
812 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
813 }
814 return NO_ERROR;
815}
816
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700817status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
818 Vector<DisplayInfo>* configs) {
819 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 return BAD_VALUE;
821 }
822
Jesse Hall692c7232012-11-08 15:41:56 -0800823 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
825 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700826 type = i;
827 break;
828 }
829 }
830
831 if (type < 0) {
832 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700833 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 // TODO: Not sure if display density should handled by SF any longer
836 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700839 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800840 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700841 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 }
843 return density;
844 }
845 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700846 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700847 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700848 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 return getDensityFromProperty("ro.sf.lcd_density"); }
850 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Steven Thomas6d8110b2017-08-31 18:24:21 -0700854 ConditionalLock _l(mStateLock,
855 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800856 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700857 DisplayInfo info = DisplayInfo();
858
Dan Stoza9e56aa02015-11-02 13:00:03 -0800859 float xdpi = hwConfig->getDpiX();
860 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700861
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700862 info.w = hwConfig->getWidth();
863 info.h = hwConfig->getHeight();
864 // Default display viewport to display width and height
865 info.viewportW = info.w;
866 info.viewportH = info.h;
867
Dan Stoza7f7da322014-05-02 15:26:25 -0700868 if (type == DisplayDevice::DISPLAY_PRIMARY) {
869 // The density of the device is provided by a build property
870 float density = Density::getBuildDensity() / 160.0f;
871 if (density == 0) {
872 // the build doesn't provide a density -- this is wrong!
873 // use xdpi instead
874 ALOGE("ro.sf.lcd_density must be defined as a build property");
875 density = xdpi / 160.0f;
876 }
877 if (Density::getEmuDensity()) {
878 // if "qemu.sf.lcd_density" is specified, it overrides everything
879 xdpi = ydpi = density = Density::getEmuDensity();
880 density /= 160.0f;
881 }
882 info.density = density;
883
884 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700885 const auto display = getDefaultDisplayDeviceLocked();
886 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700887
888 // This is for screenrecord
889 const Rect viewport = display->getViewport();
890 if (viewport.isValid()) {
891 info.viewportW = uint32_t(viewport.getWidth());
892 info.viewportH = uint32_t(viewport.getHeight());
893 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 } else {
895 // TODO: where should this value come from?
896 static const int TV_DENSITY = 213;
897 info.density = TV_DENSITY / 160.0f;
898 info.orientation = 0;
899 }
900
Dan Stoza7f7da322014-05-02 15:26:25 -0700901 info.xdpi = xdpi;
902 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900904 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905
Andy McFadden91b2ca82014-06-13 14:04:23 -0700906 // This is how far in advance a buffer must be queued for
907 // presentation at a given time. If you want a buffer to appear
908 // on the screen at time N, you must submit the buffer before
909 // (N - presentationDeadline).
910 //
911 // Normally it's one full refresh period (to give SF a chance to
912 // latch the buffer), but this can be reduced by configuring a
913 // DispSync offset. Any additional delays introduced by the hardware
914 // composer or panel must be accounted for here.
915 //
916 // We add an additional 1ms to allow for processing time and
917 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800918 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800919 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700920
921 // All non-virtual displays are currently considered secure.
922 info.secure = true;
923
Iris Chang7501ed62018-04-30 14:45:42 +0800924 if (type == DisplayDevice::DISPLAY_PRIMARY &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700925 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800926 std::swap(info.w, info.h);
927 }
928
Michael Wright28f24d02016-07-12 13:30:53 -0700929 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700930 }
931
Dan Stoza7f7da322014-05-02 15:26:25 -0700932 return NO_ERROR;
933}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700934
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700935status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
936 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700937 return BAD_VALUE;
938 }
939
940 // FIXME for now we always return stats for the primary display
941 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -0700942 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
943 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700944 return NO_ERROR;
945}
946
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700947int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
948 const auto display = getDisplayDevice(displayToken);
949 if (!display) {
950 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800951 return BAD_VALUE;
952 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700955}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700956
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
958 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700959 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700960 return;
961 }
962
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700963 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964 ALOGW("Trying to set config for virtual display");
965 return;
966 }
967
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968 display->setActiveConfig(mode);
969 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700970}
971
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700972status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700973 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700974 Vector<DisplayInfo> configs;
975 getDisplayConfigs(displayToken, &configs);
976 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
977 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
978 configs.size());
979 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700980 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700981 const auto display = getDisplayDevice(displayToken);
982 if (!display) {
983 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
984 displayToken.get());
985 } else if (display->isVirtual()) {
986 ALOGW("Attempt to set active config %d for virtual display", mode);
987 } else {
988 setActiveConfigInternal(display, mode);
989 }
990 }));
991
Mathias Agopian888c8222012-08-04 21:10:38 -0700992 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700993}
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
995 Vector<ColorMode>* outColorModes) {
996 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return BAD_VALUE;
998 }
999
Michael Wright28f24d02016-07-12 13:30:53 -07001000 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1002 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001003 type = i;
1004 break;
1005 }
1006 }
1007
1008 if (type < 0) {
1009 return type;
1010 }
1011
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001013 {
1014 ConditionalLock _l(mStateLock,
1015 std::this_thread::get_id() != mMainThreadId);
1016 modes = getHwComposer().getColorModes(type);
1017 }
Michael Wright28f24d02016-07-12 13:30:53 -07001018 outColorModes->clear();
1019 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1020
1021 return NO_ERROR;
1022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1025 if (const auto display = getDisplayDevice(displayToken)) {
1026 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001027 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001028 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001029}
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1032 Dataspace dataSpace, RenderIntent renderIntent) {
1033 ColorMode currentMode = display->getActiveColorMode();
1034 Dataspace currentDataSpace = display->getCompositionDataSpace();
1035 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001036
Peiyong Lin38e9a562018-04-10 16:24:20 -07001037 if (mode == currentMode && dataSpace == currentDataSpace &&
1038 renderIntent == currentRenderIntent) {
1039 return;
1040 }
1041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001043 ALOGW("Trying to set config for virtual display");
1044 return;
1045 }
1046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 display->setActiveColorMode(mode);
1048 display->setCompositionDataSpace(dataSpace);
1049 display->setActiveRenderIntent(renderIntent);
1050 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001051
1052 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1054 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001055}
1056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001057status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001058 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059 Vector<ColorMode> modes;
1060 getDisplayColorModes(displayToken, &modes);
1061 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1062 if (mode < ColorMode::NATIVE || !exists) {
1063 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1064 decodeColorMode(mode).c_str(), mode, displayToken.get());
1065 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001066 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067 const auto display = getDisplayDevice(displayToken);
1068 if (!display) {
1069 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1070 decodeColorMode(mode).c_str(), mode, displayToken.get());
1071 } else if (display->isVirtual()) {
1072 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1073 decodeColorMode(mode).c_str(), mode);
1074 } else {
1075 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1076 RenderIntent::COLORIMETRIC);
1077 }
1078 }));
1079
Michael Wright28f24d02016-07-12 13:30:53 -07001080 return NO_ERROR;
1081}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001082
Svetoslavd85084b2014-03-20 10:28:31 -07001083status_t SurfaceFlinger::clearAnimationFrameStats() {
1084 Mutex::Autolock _l(mStateLock);
1085 mAnimFrameTracker.clearStats();
1086 return NO_ERROR;
1087}
1088
1089status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1090 Mutex::Autolock _l(mStateLock);
1091 mAnimFrameTracker.getStats(outStats);
1092 return NO_ERROR;
1093}
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1096 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001097 Mutex::Autolock _l(mStateLock);
1098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099 const auto display = getDisplayDeviceLocked(displayToken);
1100 if (!display) {
1101 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001102 return BAD_VALUE;
1103 }
1104
Peiyong Linfb069302018-04-25 14:34:31 -07001105 // At this point the DisplayDeivce should already be set up,
1106 // meaning the luminance information is already queried from
1107 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001109 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1110 capabilities.getDesiredMaxLuminance(),
1111 capabilities.getDesiredMaxAverageLuminance(),
1112 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001113
1114 return NO_ERROR;
1115}
1116
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001117status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001118 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001119 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001120
Chia-I Wu90f669f2017-10-05 14:24:41 -07001121 if (mInjectVSyncs == enable) {
1122 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001123 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001124
Ana Krulec98b5b242018-08-10 15:03:23 -07001125 // TODO(akrulec): Part of the Injector should be refactored, so that it
1126 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001127 if (enable) {
1128 ALOGV("VSync Injections enabled");
1129 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001130 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001131 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001132 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001133 impl::EventThread::InterceptVSyncsCallback(),
1134 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001135 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001136 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001137 } else {
1138 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001139 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001140 }
1141
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001143 }));
1144
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 return NO_ERROR;
1146}
1147
1148status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 Mutex::Autolock _l(mStateLock);
1150
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001151 if (!mInjectVSyncs) {
1152 ALOGE("VSync Injections not enabled");
1153 return BAD_VALUE;
1154 }
1155 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1156 ALOGV("Injecting VSync inside SurfaceFlinger");
1157 mVSyncInjector->onInjectSyncEvent(when);
1158 }
1159 return NO_ERROR;
1160}
1161
Lloyd Pique755e3192018-01-31 16:46:15 -08001162status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1163 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001164 // Try to acquire a lock for 1s, fail gracefully
1165 const status_t err = mStateLock.timedLock(s2ns(1));
1166 const bool locked = (err == NO_ERROR);
1167 if (!locked) {
1168 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1169 return TIMED_OUT;
1170 }
1171
1172 outLayers->clear();
1173 mCurrentState.traverseInZOrder([&](Layer* layer) {
1174 outLayers->push_back(layer->getLayerDebugInfo());
1175 });
1176
1177 mStateLock.unlock();
1178 return NO_ERROR;
1179}
1180
Peiyong Lin0256f722018-08-31 15:45:10 -07001181status_t SurfaceFlinger::getCompositionPreference(Dataspace* outDataSpace,
1182 ui::PixelFormat* outPixelFormat) const {
1183 *outDataSpace = compositionDataSpace;
1184 *outPixelFormat = compositionPixelFormat;
1185 return NO_ERROR;
1186}
1187
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001188// ----------------------------------------------------------------------------
1189
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001190sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1191 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001192 if (mUseScheduler) {
1193 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1194 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1195 } else {
1196 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1197 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001198 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001199 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1200 return mSFEventThread->createEventConnection();
1201 } else {
1202 return mEventThread->createEventConnection();
1203 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001204 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001205}
1206
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001207// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001208
1209void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001210 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001211}
1212
1213void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001214 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001215}
1216
1217void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001218 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001219}
1220
1221void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001222 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001223 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001224}
1225
1226status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001227 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001228 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001229}
1230
1231status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001232 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001233 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234 if (res == NO_ERROR) {
1235 msg->wait();
1236 }
1237 return res;
1238}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001239
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001240void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001241 do {
1242 waitForEvent();
1243 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244}
1245
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246void SurfaceFlinger::enableHardwareVsync() {
1247 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001248 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001249 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001250 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001251 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001252 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001253}
1254
Jesse Hall948fe0c2013-10-14 12:56:09 -07001255void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001256 Mutex::Autolock _l(mHWVsyncLock);
1257
Jesse Hall948fe0c2013-10-14 12:56:09 -07001258 if (makeAvailable) {
1259 mHWVsyncAvailable = true;
1260 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001261 // Hardware vsync is not currently available, so abort the resync
1262 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001263 return;
1264 }
1265
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001266 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1267 if (!getHwComposer().isConnected(displayId)) {
1268 return;
1269 }
1270
1271 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001272 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001273
Lloyd Pique41be5d22018-06-21 13:11:48 -07001274 mPrimaryDispSync->reset();
1275 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001276
1277 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001278 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001279 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001280 mPrimaryHWVsyncEnabled = true;
1281 }
1282}
1283
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001285 Mutex::Autolock _l(mHWVsyncLock);
1286 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001288 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289 mPrimaryHWVsyncEnabled = false;
1290 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 if (makeUnavailable) {
1292 mHWVsyncAvailable = false;
1293 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001294}
1295
Tim Murray4a4e4a22016-04-19 16:29:23 +00001296void SurfaceFlinger::resyncWithRateLimit() {
1297 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001298
1299 // No explicit locking is needed here since EventThread holds a lock while calling this method
1300 static nsecs_t sLastResyncAttempted = 0;
1301 const nsecs_t now = systemTime();
1302 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001303 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001304 }
Dan Stoza57164302017-05-08 14:03:54 -07001305 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001306}
1307
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001308void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1309 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001310 ATRACE_NAME("SF onVsync");
1311
Steven Thomas3cfac282017-02-06 12:29:30 -08001312 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001313 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001314 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001315 return;
1316 }
1317
1318 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001319 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001320 return;
1321 }
1322
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001323 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1324 // For now, we don't do anything with external display vsyncs.
1325 return;
1326 }
1327
Jamie Gennisd1700752013-10-14 12:22:52 -07001328 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329
Jamie Gennisd1700752013-10-14 12:22:52 -07001330 { // Scope for the lock
1331 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001332 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001333 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001335 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001336
1337 if (needsHwVsync) {
1338 enableHardwareVsync();
1339 } else {
1340 disableHardwareVsync(false);
1341 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001342}
1343
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001344void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001345 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1346 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001347}
1348
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001349void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001350 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001351 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001352 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001353
Lloyd Piqueba04e622017-12-14 17:11:26 -08001354 // Ignore events that do not have the right sequenceId.
1355 if (sequenceId != getBE().mComposerSequenceId) {
1356 return;
1357 }
1358
Steven Thomasb02664d2017-07-26 18:48:28 -07001359 // Only lock if we're not on the main thread. This function is normally
1360 // called on a hwbinder thread, but for the primary display it's called on
1361 // the main thread with the state lock already held, so don't attempt to
1362 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001363 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001364
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001365 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001366
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001367 if (std::this_thread::get_id() == mMainThreadId) {
1368 // Process all pending hot plug events immediately if we are on the main thread.
1369 processDisplayHotplugEventsLocked();
1370 }
1371
Lloyd Piqueba04e622017-12-14 17:11:26 -08001372 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001373}
1374
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001375void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001380 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001381}
1382
Dan Stoza9e56aa02015-11-02 13:00:03 -08001383void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001384 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001385 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001386 getHwComposer().setVsyncEnabled(disp,
1387 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001388}
1389
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001390// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001391void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001392 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001393 // Clear the drawing state so that the logic inside of
1394 // handleTransactionLocked will fire. It will determine the delta between
1395 // mCurrentState and mDrawingState and re-apply all changes when we make the
1396 // transition.
1397 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001398 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001399 mDisplays.clear();
1400}
1401
Steven Thomas050b2c82017-03-06 11:45:16 -08001402void SurfaceFlinger::updateVrFlinger() {
1403 if (!mVrFlinger)
1404 return;
1405 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001406 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001407 return;
1408 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001409
David Sodman105b7dc2017-11-04 20:28:14 -07001410 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001411 ALOGE("Vr flinger is only supported for remote hardware composer"
1412 " service connections. Ignoring request to transition to vr"
1413 " flinger.");
1414 mVrFlingerRequestsDisplay = false;
1415 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001416 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001417
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001418 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001419
Steven Thomas0123ac62018-07-12 11:32:34 -07001420 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001421 LOG_ALWAYS_FATAL_IF(!display);
1422 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001423 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1424 // called below. Clear the reference now so we don't accidentally use it
1425 // later.
1426 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001427
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001433 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001434 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1435 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001436 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001437
David Sodman105b7dc2017-11-04 20:28:14 -07001438 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1439 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001440
1441 if (vrFlingerRequestsDisplay) {
1442 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001443 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001444
1445 mVisibleRegionsDirty = true;
1446 invalidateHwcGeometry();
1447
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001448 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001449 display = getDefaultDisplayDeviceLocked();
1450 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001451 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001452
Steven Thomasb02664d2017-07-26 18:48:28 -07001453 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001454 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 const nsecs_t period = activeConfig->getVsyncPeriod();
1456 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001457
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001458 // The present fences returned from vr_hwc are not an accurate
1459 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001460 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1461 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001462
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 // Use phase of 0 since phase is not known.
1464 // Use latency of 0, which will snap to the ideal latency.
1465 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001466
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001467 resyncToHardwareVsync(false);
1468
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001469 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471}
1472
Mathias Agopian4fec8732012-06-29 14:12:52 -07001473void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001474 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001475 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001476 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001477 bool frameMissed = !mHadClientComposition &&
1478 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001479 (mPreviousPresentFence->getSignalTime() ==
1480 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001481 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001482 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001483 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001484 mTimeStats.incrementMissedFrames();
1485 if (mPropagateBackpressure) {
1486 signalLayerUpdate();
1487 break;
1488 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001489 }
Dan Stoza50182882016-07-08 12:02:20 -07001490
Steven Thomas050b2c82017-03-06 11:45:16 -08001491 // Now that we're going to make it to the handleMessageTransaction()
1492 // call below it's safe to call updateVrFlinger(), which will
1493 // potentially trigger a display handoff.
1494 updateVrFlinger();
1495
Dan Stoza6b9454d2014-11-07 16:00:59 -08001496 bool refreshNeeded = handleMessageTransaction();
1497 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001498 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001499 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001500 // Signal a refresh if a transaction modified the window state,
1501 // a new buffer was latched, or if HWC has requested a full
1502 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001503 signalRefresh();
1504 }
1505 break;
1506 }
1507 case MessageQueue::REFRESH: {
1508 handleMessageRefresh();
1509 break;
1510 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511 }
1512}
1513
Dan Stoza6b9454d2014-11-07 16:00:59 -08001514bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001515 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001516 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001517 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001518 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001519 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001520 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521}
1522
Mathias Agopian4fec8732012-06-29 14:12:52 -07001523void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001524 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001525
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001526 mRefreshPending = false;
1527
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001528 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001529 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001530 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001531 calculateWorkingSet();
David Sodman10a41ff2018-08-05 12:14:17 -07001532
David Sodmanfa9b2af2017-12-24 13:28:59 -08001533 for (const auto& [token, display] : mDisplays) {
David Sodman10a41ff2018-08-05 12:14:17 -07001534 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001535 beginFrame(display);
David Sodman10a41ff2018-08-05 12:14:17 -07001536 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
1537 setUpHWComposer(compositionInfo);
1538 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001539 prepareFrame(display);
1540 doDebugFlashRegions(display, repaintEverything);
1541 doComposition(display, repaintEverything);
1542 }
1543
Adrian Roos1e1a1282017-11-01 19:05:31 +01001544 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001545 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001546
1547 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001548 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001549
Dan Stozabfbffeb2016-07-21 14:49:33 -07001550 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001551 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001552 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001553 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001554 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001555
Alec Mouri86770e52018-09-24 22:40:58 +00001556 // Setup RenderEngine sync fences if native sync is supported.
1557 if (getBE().mRenderEngine->useNativeFenceSync()) {
1558 if (mHadClientComposition) {
1559 base::unique_fd flushFence(getRenderEngine().flush());
1560 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1561 getBE().flushFence = new Fence(std::move(flushFence));
1562 } else {
1563 // Cleanup for hygiene.
1564 getBE().flushFence = Fence::NO_FENCE;
1565 }
1566 }
1567
Jorim Jaggi90535212018-05-23 23:44:06 +02001568 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001569
David Sodman7e4ae112018-02-09 15:02:28 -08001570 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001571 for (const auto& [token, display] : mDisplays) {
1572 const auto displayId = display->getId();
David Sodman7e4ae112018-02-09 15:02:28 -08001573 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[displayId]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001574 compositionInfo.hwc.hwcLayer = nullptr;
1575 }
David Sodmanba340492018-08-05 21:51:33 -07001576 }
David Sodman7e4ae112018-02-09 15:02:28 -08001577
1578 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001579}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580
David Sodmanfa9b2af2017-12-24 13:28:59 -08001581
1582bool SurfaceFlinger::handleMessageInvalidate() {
1583 ATRACE_CALL();
1584 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001585}
1586
David Sodman79bba0e2018-08-05 18:07:49 -07001587void SurfaceFlinger::calculateWorkingSet() {
1588 ATRACE_CALL();
1589 ALOGV(__FUNCTION__);
1590
David Sodman79bba0e2018-08-05 18:07:49 -07001591 // build the h/w work list
1592 if (CC_UNLIKELY(mGeometryInvalid)) {
1593 mGeometryInvalid = false;
1594 for (const auto& [token, display] : mDisplays) {
1595 const auto displayId = display->getId();
1596 if (displayId >= 0) {
1597 const Vector<sp<Layer>>& currentLayers(
1598 display->getVisibleLayersSortedByZ());
1599 for (size_t i = 0; i < currentLayers.size(); i++) {
1600 const auto& layer = currentLayers[i];
1601
1602 if (!layer->hasHwcLayer(displayId)) {
1603 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
1604 layer->forceClientComposition(displayId);
1605 continue;
1606 }
1607 }
1608
1609 layer->setGeometry(display, i);
1610 if (mDebugDisableHWC || mDebugRegion) {
1611 layer->forceClientComposition(displayId);
1612 }
1613 }
1614 }
1615 }
1616 }
1617
1618 // Set the per-frame data
1619 for (const auto& [token, display] : mDisplays) {
1620 const auto displayId = display->getId();
1621 if (displayId < 0) {
1622 continue;
1623 }
1624
1625 if (mDrawingState.colorMatrixChanged) {
1626 display->setColorTransform(mDrawingState.colorMatrix);
1627 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
1628 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1629 "display %d: %d", displayId, result);
1630 }
1631 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1632 if (layer->isHdrY410()) {
1633 layer->forceClientComposition(displayId);
1634 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1635 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1636 !display->hasHDR10Support()) {
1637 layer->forceClientComposition(displayId);
1638 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1639 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1640 !display->hasHLGSupport()) {
1641 layer->forceClientComposition(displayId);
1642 }
1643
1644 if (layer->getForceClientComposition(displayId)) {
1645 ALOGV("[%s] Requesting Client composition", layer->getName().string());
1646 layer->setCompositionType(displayId, HWC2::Composition::Client);
1647 continue;
1648 }
1649
1650 layer->setPerFrameData(display);
1651 }
1652
Peiyong Lin13effd12018-07-24 17:01:47 -07001653 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001654 ColorMode colorMode;
1655 Dataspace dataSpace;
1656 RenderIntent renderIntent;
1657 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1658 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1659 }
1660 }
1661
1662 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001663
1664 for (const auto& [token, display] : mDisplays) {
David Sodman15fb96e2018-01-07 10:23:24 -08001665 const auto displayId = display->getId();
1666 getBE().mCompositionInfo[displayId].clear();
David Sodmanba340492018-08-05 21:51:33 -07001667 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1668 auto displayId = display->getId();
1669 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
1670 if (!layer->setHwcLayer(displayId)) {
1671 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1672 }
David Sodman15fb96e2018-01-07 10:23:24 -08001673 layer->getBE().compositionInfo.hwc.displayId = displayId;
1674 getBE().mCompositionInfo[displayId].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001675 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1676 }
1677 }
David Sodman79bba0e2018-08-05 18:07:49 -07001678}
1679
David Sodmanfa9b2af2017-12-24 13:28:59 -08001680void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001681{
David Sodmanfb95bcc2017-12-22 15:45:30 -08001682 const auto displayId = display->getId();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 // is debugging enabled
1684 if (CC_LIKELY(!mDebugRegion))
1685 return;
1686
David Sodmanfa9b2af2017-12-24 13:28:59 -08001687 if (display->isPoweredOn()) {
1688 // transform the dirty region into this screen's coordinate space
1689 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1690 if (!dirtyRegion.isEmpty()) {
1691 // redraw the whole screen
1692 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001693
David Sodmanfa9b2af2017-12-24 13:28:59 -08001694 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001695 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001696 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001697
David Sodmanfa9b2af2017-12-24 13:28:59 -08001698 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001699 }
1700 }
1701
David Sodmanfa9b2af2017-12-24 13:28:59 -08001702 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703
1704 if (mDebugRegion > 1) {
1705 usleep(mDebugRegion * 1000);
1706 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001707
David Sodmanfa9b2af2017-12-24 13:28:59 -08001708 if (display->isPoweredOn()) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08001709 status_t result = display->prepareFrame(
1710 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001711 ALOGE_IF(result != NO_ERROR,
1712 "prepareFrame for display %d failed:"
1713 " %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001714 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001715 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001716}
1717
Adrian Roos1e1a1282017-11-01 19:05:31 +01001718void SurfaceFlinger::doTracing(const char* where) {
1719 ATRACE_CALL();
1720 ATRACE_NAME(where);
1721 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001722 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001723 }
1724}
1725
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001726void SurfaceFlinger::logLayerStats() {
1727 ATRACE_CALL();
1728 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001729 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001730 if (display->isPrimary()) {
1731 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001732 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001733 }
1734 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001735
1736 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001737 }
1738}
1739
David Sodman2b406362017-12-15 13:33:47 -08001740void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001741{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001742 ATRACE_CALL();
1743 ALOGV("preComposition");
1744
David Sodman2b406362017-12-15 13:33:47 -08001745 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1746
Mathias Agopiancd60f992012-08-16 16:28:27 -07001747 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001748 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001749 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001750 needExtraInvalidate = true;
1751 }
Robert Carr2047fae2016-11-28 14:09:09 -08001752 });
1753
Mathias Agopiancd60f992012-08-16 16:28:27 -07001754 if (needExtraInvalidate) {
1755 signalLayerUpdate();
1756 }
1757}
1758
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001759void SurfaceFlinger::updateCompositorTiming(
1760 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1761 std::shared_ptr<FenceTime>& presentFenceTime) {
1762 // Update queue of past composite+present times and determine the
1763 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001764 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001765 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001766 while (!getBE().mCompositePresentTimes.empty()) {
1767 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001768 // Cached values should have been updated before calling this method,
1769 // which helps avoid duplicate syscalls.
1770 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1771 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1772 break;
1773 }
1774 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001775 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001776 }
1777
1778 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001779 while (getBE().mCompositePresentTimes.size() > 16) {
1780 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 }
1782
Brian Andersond0010582017-03-07 13:20:31 -08001783 setCompositorTimingSnapped(
1784 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1785}
1786
1787void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1788 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001789 // Integer division and modulo round toward 0 not -inf, so we need to
1790 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001791 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001792 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1793 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1794
Brian Andersond0010582017-03-07 13:20:31 -08001795 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1796 if (idealLatency <= 0) {
1797 idealLatency = vsyncInterval;
1798 }
1799
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001800 // Snap the latency to a value that removes scheduling jitter from the
1801 // composition and present times, which often have >1ms of jitter.
1802 // Reducing jitter is important if an app attempts to extrapolate
1803 // something (such as user input) to an accurate diasplay time.
1804 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1805 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001806 nsecs_t bias = vsyncInterval / 2;
1807 int64_t extraVsyncs =
1808 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1809 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1810 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001811
David Sodman99974d22017-11-28 12:04:33 -08001812 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1813 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1814 getBE().mCompositorTiming.interval = vsyncInterval;
1815 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001816}
1817
David Sodman2b406362017-12-15 13:33:47 -08001818void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001819{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001820 ATRACE_CALL();
1821 ALOGV("postComposition");
1822
Brian Anderson3546a3f2016-07-14 11:51:14 -07001823 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001824 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001825 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001826 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001827 }
1828
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001829 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001830 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001831
David Sodman73beded2017-11-15 11:56:06 -08001832 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001833 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001834 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001835 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001836 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001837 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001838 } else {
1839 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1840 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001841
David Sodman73beded2017-11-15 11:56:06 -08001842 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001843 mPreviousPresentFence =
1844 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1845 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001846 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001847
Lloyd Pique41be5d22018-06-21 13:11:48 -07001848 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1849 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001850
David Sodman2b406362017-12-15 13:33:47 -08001851 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001852 // when we started doing work for this frame, but that should be okay
1853 // since updateCompositorTiming has snapping logic.
1854 updateCompositorTiming(
David Sodman2b406362017-12-15 13:33:47 -08001855 vsyncPhase, vsyncInterval, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001856 CompositorTiming compositorTiming;
1857 {
David Sodman99974d22017-11-28 12:04:33 -08001858 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1859 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001860 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861
Robert Carr2047fae2016-11-28 14:09:09 -08001862 mDrawingState.traverseInZOrder([&](Layer* layer) {
1863 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001864 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001865 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001866 recordBufferingStats(layer->getName().string(),
1867 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001868 }
Robert Carr2047fae2016-11-28 14:09:09 -08001869 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001870
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001871 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001872 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001873 enableHardwareVsync();
1874 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001875 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001876 }
1877 }
1878
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001879 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001880 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001881 enableHardwareVsync();
1882 }
1883 }
1884
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001885 if (mAnimCompositionPending) {
1886 mAnimCompositionPending = false;
1887
Brian Anderson4e606e32017-03-16 15:34:57 -07001888 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001889 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001890 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001891 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001892 // The HWC doesn't support present fences, so use the refresh
1893 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001894 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001895 mAnimFrameTracker.setActualPresentTime(presentTime);
1896 }
1897 mAnimFrameTracker.advanceFrame();
1898 }
Dan Stozab90cf072015-03-05 11:05:59 -08001899
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001900 mTimeStats.incrementTotalFrames();
1901 if (mHadClientComposition) {
1902 mTimeStats.incrementClientCompositionFrames();
1903 }
1904
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001905 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001906 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001907 return;
1908 }
1909
1910 nsecs_t currentTime = systemTime();
1911 if (mHasPoweredOff) {
1912 mHasPoweredOff = false;
1913 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001914 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001916 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1917 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001918 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001919 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001920 }
David Sodman4a36e932017-11-07 14:29:47 -08001921 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001922 }
David Sodman4a36e932017-11-07 14:29:47 -08001923 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001924
1925 {
1926 std::lock_guard lock(mTexturePoolMutex);
1927 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1928 if (refillCount > 0) {
1929 const size_t offset = mTexturePool.size();
1930 mTexturePool.resize(mTexturePoolSize);
1931 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1932 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1933 }
1934 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001935}
1936
1937void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001938 ATRACE_CALL();
1939 ALOGV("rebuildLayerStacks");
1940
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001942 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001943 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001944 mVisibleRegionsDirty = false;
1945 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001946
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001947 for (const auto& pair : mDisplays) {
1948 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001949 Region opaqueRegion;
1950 Region dirtyRegion;
1951 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001952 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07001953 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001954 const Rect bounds = display->getBounds();
1955 if (display->isPoweredOn()) {
1956 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001957
Jeff Sharkey76488112017-02-27 14:15:18 -07001958 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001959 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001960 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001961 Region drawRegion(tr.transform(
1962 layer->visibleNonTransparentRegion));
1963 drawRegion.andSelf(bounds);
1964 if (!drawRegion.isEmpty()) {
1965 layersSortedByZ.add(layer);
1966 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001967 // Clear out the HWC layer if this layer was
1968 // previously visible, but no longer is
1969 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001970 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001971 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001972 // WM changes display->layerStack upon sleep/awake.
1973 // Here we make sure we delete the HWC layers even if
1974 // WM changed their layer stack.
1975 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001976 }
1977
1978 // If a layer is not going to get a release fence because
1979 // it is invisible, but it is also going to release its
1980 // old buffer, add it to the list of layers needing
1981 // fences.
1982 if (hwcLayerDestroyed) {
1983 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1984 mLayersWithQueuedFrames.cend(), layer);
1985 if (found != mLayersWithQueuedFrames.cend()) {
1986 layersNeedingFences.add(layer);
1987 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001988 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001989 });
1990 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001991 display->setVisibleLayersSortedByZ(layersSortedByZ);
1992 display->setLayersNeedingFences(layersNeedingFences);
1993 display->undefinedRegion.set(bounds);
1994 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1995 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001996 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001997 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001999
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002000// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002001// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002002// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002003// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002004// The returned HDR data space is one of
2005// - Dataspace::UNKNOWN
2006// - Dataspace::BT2020_HLG
2007// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002008Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2009 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07002010 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002011 *outHdrDataSpace = Dataspace::UNKNOWN;
2012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002013 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002014 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002015 case Dataspace::V0_SCRGB:
2016 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002017 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002018 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002019 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002020 case Dataspace::BT2020_PQ:
2021 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002022 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002023 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002024 case Dataspace::BT2020_HLG:
2025 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002026 // When there's mixed PQ content and HLG content, we set the HDR
2027 // data space to be BT2020_PQ and convert HLG to PQ.
2028 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2029 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002030 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002031 break;
2032 default:
2033 break;
2034 }
Romain Guy54f154a2017-10-24 21:40:32 +01002035 }
2036
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002037 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002038}
2039
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002040// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002041void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2042 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002043 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2044 *outMode = ColorMode::NATIVE;
2045 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002046 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002047 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002048 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002049
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002050 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002051 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002052
Peiyong Lindfde5112018-06-05 10:58:41 -07002053 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002054 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002055 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002056 if (isHdr) {
2057 bestDataSpace = hdrDataSpace;
2058 }
2059
Chia-I Wu0d711262018-05-21 15:19:35 -07002060 RenderIntent intent;
2061 switch (mDisplayColorSetting) {
2062 case DisplayColorSetting::MANAGED:
2063 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002064 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002065 break;
2066 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002067 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002068 break;
2069 default: // vendor display color setting
2070 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2071 break;
2072 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002073
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002074 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002075}
2076
David Sodman10a41ff2018-08-05 12:14:17 -07002077void SurfaceFlinger::configureSidebandComposition(const CompositionInfo& compositionInfo) const
2078{
2079 HWC2::Error error;
2080 LOG_ALWAYS_FATAL_IF(compositionInfo.hwc.sidebandStream == nullptr,
2081 "CompositionType is sideband, but sideband stream is nullptr");
2082 error = (compositionInfo.hwc.hwcLayer)
2083 ->setSidebandStream(compositionInfo.hwc.sidebandStream->handle());
2084 if (error != HWC2::Error::None) {
2085 ALOGE("[SF] Failed to set sideband stream %p: %s (%d)",
2086 compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
2087 static_cast<int32_t>(error));
2088 }
2089}
2090
2091void SurfaceFlinger::configureHwcCommonData(const CompositionInfo& compositionInfo) const
2092{
2093 HWC2::Error error;
2094
2095 if (!compositionInfo.hwc.skipGeometry) {
2096 error = (compositionInfo.hwc.hwcLayer)->setBlendMode(compositionInfo.hwc.blendMode);
2097 ALOGE_IF(error != HWC2::Error::None,
2098 "[SF] Failed to set blend mode %s:"
2099 " %s (%d)",
2100 to_string(compositionInfo.hwc.blendMode).c_str(), to_string(error).c_str(),
2101 static_cast<int32_t>(error));
2102
2103 error = (compositionInfo.hwc.hwcLayer)->setDisplayFrame(compositionInfo.hwc.displayFrame);
2104 ALOGE_IF(error != HWC2::Error::None,
2105 "[SF] Failed to set the display frame [%d, %d, %d, %d] %s (%d)",
2106 compositionInfo.hwc.displayFrame.left,
2107 compositionInfo.hwc.displayFrame.right,
2108 compositionInfo.hwc.displayFrame.top,
2109 compositionInfo.hwc.displayFrame.bottom,
2110 to_string(error).c_str(), static_cast<int32_t>(error));
2111
2112 error = (compositionInfo.hwc.hwcLayer)->setSourceCrop(compositionInfo.hwc.sourceCrop);
2113 ALOGE_IF(error != HWC2::Error::None,
2114 "[SF] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: %s (%d)",
2115 compositionInfo.hwc.sourceCrop.left,
2116 compositionInfo.hwc.sourceCrop.right,
2117 compositionInfo.hwc.sourceCrop.top,
2118 compositionInfo.hwc.sourceCrop.bottom,
2119 to_string(error).c_str(), static_cast<int32_t>(error));
2120
2121 error = (compositionInfo.hwc.hwcLayer)->setPlaneAlpha(compositionInfo.hwc.alpha);
2122 ALOGE_IF(error != HWC2::Error::None,
2123 "[SF] Failed to set plane alpha %.3f: "
2124 "%s (%d)",
2125 compositionInfo.hwc.alpha,
2126 to_string(error).c_str(), static_cast<int32_t>(error));
2127
2128
2129 error = (compositionInfo.hwc.hwcLayer)->setZOrder(compositionInfo.hwc.z);
2130 ALOGE_IF(error != HWC2::Error::None,
2131 "[SF] Failed to set Z %u: %s (%d)",
2132 compositionInfo.hwc.z,
2133 to_string(error).c_str(), static_cast<int32_t>(error));
2134
2135 error = (compositionInfo.hwc.hwcLayer)
2136 ->setInfo(compositionInfo.hwc.type, compositionInfo.hwc.appId);
2137 ALOGE_IF(error != HWC2::Error::None,
2138 "[SF] Failed to set info (%d)",
2139 static_cast<int32_t>(error));
2140
2141 error = (compositionInfo.hwc.hwcLayer)->setTransform(compositionInfo.hwc.transform);
2142 ALOGE_IF(error != HWC2::Error::None,
2143 "[SF] Failed to set transform %s: "
2144 "%s (%d)",
2145 to_string(compositionInfo.hwc.transform).c_str(), to_string(error).c_str(),
2146 static_cast<int32_t>(error));
2147 }
2148
2149 error = (compositionInfo.hwc.hwcLayer)->setCompositionType(compositionInfo.compositionType);
2150 ALOGE_IF(error != HWC2::Error::None,
2151 "[SF] Failed to set composition type: %s (%d)",
2152 to_string(error).c_str(), static_cast<int32_t>(error));
2153
2154 error = (compositionInfo.hwc.hwcLayer)->setDataspace(compositionInfo.hwc.dataspace);
2155 ALOGE_IF(error != HWC2::Error::None,
2156 "[SF] Failed to set dataspace: %s (%d)",
2157 to_string(error).c_str(), static_cast<int32_t>(error));
2158
2159 error = (compositionInfo.hwc.hwcLayer)->setPerFrameMetadata(
2160 compositionInfo.hwc.supportedPerFrameMetadata, compositionInfo.hwc.hdrMetadata);
2161 ALOGE_IF(error != HWC2::Error::None && error != HWC2::Error::Unsupported,
2162 "[SF] Failed to set hdrMetadata: %s (%d)",
2163 to_string(error).c_str(), static_cast<int32_t>(error));
2164
2165 if (compositionInfo.compositionType == HWC2::Composition::SolidColor) {
2166 error = (compositionInfo.hwc.hwcLayer)->setColor(compositionInfo.hwc.color);
2167 ALOGE_IF(error != HWC2::Error::None,
2168 "[SF] Failed to set color: %s (%d)",
2169 to_string(error).c_str(), static_cast<int32_t>(error));
2170 }
2171
2172 error = (compositionInfo.hwc.hwcLayer)->setVisibleRegion(compositionInfo.hwc.visibleRegion);
2173 ALOGE_IF(error != HWC2::Error::None,
2174 "[SF] Failed to set visible region: %s (%d)",
2175 to_string(error).c_str(), static_cast<int32_t>(error));
2176
2177 error = (compositionInfo.hwc.hwcLayer)->setSurfaceDamage(compositionInfo.hwc.surfaceDamage);
2178 ALOGE_IF(error != HWC2::Error::None,
2179 "[SF] Failed to set surface damage: %s (%d)",
2180 to_string(error).c_str(), static_cast<int32_t>(error));
2181}
2182
2183void SurfaceFlinger::configureDeviceComposition(const CompositionInfo& compositionInfo) const
2184{
2185 HWC2::Error error;
2186
2187 if (compositionInfo.hwc.fence) {
2188 error = (compositionInfo.hwc.hwcLayer)->setBuffer(compositionInfo.mBufferSlot,
2189 compositionInfo.mBuffer, compositionInfo.hwc.fence);
2190 ALOGE_IF(error != HWC2::Error::None,
2191 "[SF] Failed to set buffer: %s (%d)",
2192 to_string(error).c_str(), static_cast<int32_t>(error));
2193 }
2194}
2195
David Sodmanfa9b2af2017-12-24 13:28:59 -08002196void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002197{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002198 bool dirty = !display->getDirtyRegion(false).isEmpty();
2199 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2200 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002201
David Sodmanfa9b2af2017-12-24 13:28:59 -08002202 // If nothing has changed (!dirty), don't recompose.
2203 // If something changed, but we don't currently have any visible layers,
2204 // and didn't when we last did a composition, then skip it this time.
2205 // The second rule does two things:
2206 // - When all layers are removed from a display, we'll emit one black
2207 // frame, then nothing more until we get new layers.
2208 // - When a display is created with a private layer stack, we won't
2209 // emit any black frames until a layer is added to the layer stack.
2210 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002211
Chih-Hung Hsieh617bb202018-08-22 14:45:27 -07002212 ALOGV_IF(display->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
2213 "id[%d]: %s composition (%sdirty %sempty %swasEmpty)", display->getId(),
David Sodmanfa9b2af2017-12-24 13:28:59 -08002214 mustRecompose ? "doing" : "skipping",
2215 dirty ? "+" : "-",
2216 empty ? "+" : "-",
2217 wasEmpty ? "+" : "-");
David Sodman2b406362017-12-15 13:33:47 -08002218
David Sodmanfa9b2af2017-12-24 13:28:59 -08002219 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002220
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221 if (mustRecompose) {
2222 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002223 }
2224}
2225
David Sodmanfa9b2af2017-12-24 13:28:59 -08002226void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002227{
David Sodmanfb95bcc2017-12-22 15:45:30 -08002228 const auto displayId = display->getId();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002229 if (!display->isPoweredOn()) {
2230 return;
David Sodman2b406362017-12-15 13:33:47 -08002231 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002232
David Sodmanfb95bcc2017-12-22 15:45:30 -08002233 status_t result = display->prepareFrame(
2234 *getBE().mHwc, getBE().mCompositionInfo[displayId]);
David Sodmanfa9b2af2017-12-24 13:28:59 -08002235 ALOGE_IF(result != NO_ERROR,
2236 "prepareFrame for display %d failed:"
2237 " %d (%s)",
2238 display->getId(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002239}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002240
David Sodman10a41ff2018-08-05 12:14:17 -07002241void SurfaceFlinger::setUpHWComposer(const CompositionInfo& compositionInfo) {
2242 ATRACE_CALL();
2243 ALOGV("setUpHWComposer");
2244
2245 switch (compositionInfo.compositionType)
2246 {
2247 case HWC2::Composition::Invalid:
David Sodmana6d42332018-08-29 14:07:04 -07002248 break;
2249
David Sodman10a41ff2018-08-05 12:14:17 -07002250 case HWC2::Composition::Client:
David Sodmana6d42332018-08-29 14:07:04 -07002251 if (compositionInfo.hwc.hwcLayer) {
2252 auto error = (compositionInfo.hwc.hwcLayer)->
2253 setCompositionType(compositionInfo.compositionType);
2254 ALOGE_IF(error != HWC2::Error::None,
2255 "[SF] Failed to set composition type: %s (%d)",
2256 to_string(error).c_str(), static_cast<int32_t>(error));
2257 }
David Sodman10a41ff2018-08-05 12:14:17 -07002258 break;
2259
2260 case HWC2::Composition::Sideband:
2261 configureHwcCommonData(compositionInfo);
2262 configureSidebandComposition(compositionInfo);
2263 break;
2264
2265 case HWC2::Composition::SolidColor:
2266 configureHwcCommonData(compositionInfo);
2267 break;
2268
2269 case HWC2::Composition::Device:
2270 case HWC2::Composition::Cursor:
2271 configureHwcCommonData(compositionInfo);
2272 configureDeviceComposition(compositionInfo);
2273 break;
2274 }
2275}
2276
David Sodmanfa9b2af2017-12-24 13:28:59 -08002277void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002278 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002279 ALOGV("doComposition");
2280
David Sodmanfa9b2af2017-12-24 13:28:59 -08002281 if (display->isPoweredOn()) {
2282 // transform the dirty region into this screen's coordinate space
2283 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002284
David Sodmanfa9b2af2017-12-24 13:28:59 -08002285 // repaint the framebuffer (if needed)
2286 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002287
David Sodmanfa9b2af2017-12-24 13:28:59 -08002288 display->dirtyRegion.clear();
2289 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002290 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002291 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002292}
2293
David Sodmanfa9b2af2017-12-24 13:28:59 -08002294void SurfaceFlinger::postFrame()
2295{
2296 // |mStateLock| not needed as we are on the main thread
2297 if (getBE().mHwc->isConnected(HWC_DISPLAY_PRIMARY)) {
2298 uint32_t flipCount = getDefaultDisplayDeviceLocked()->getPageFlipCount();
2299 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2300 logFrameStats();
2301 }
2302 }
2303}
2304
2305void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002306{
Mathias Agopian841cde52012-03-01 15:44:37 -08002307 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002308 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002309
David Sodmanfa9b2af2017-12-24 13:28:59 -08002310 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002311
David Sodmanfa9b2af2017-12-24 13:28:59 -08002312 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002313 const auto displayId = display->getId();
2314 if (displayId >= 0) {
2315 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002316 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002317 display->onSwapBuffersCompleted();
2318 display->makeCurrent();
David Sodman10a41ff2018-08-05 12:14:17 -07002319 for (auto& compositionInfo : getBE().mCompositionInfo[displayId]) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002320 sp<Fence> releaseFence = Fence::NO_FENCE;
Chia-I Wu7b549592017-11-15 09:14:57 -08002321 // The layer buffer from the previous frame (if any) is released
2322 // by HWC only when the release fence from this frame (if any) is
2323 // signaled. Always get the release fence from HWC first.
David Sodman10a41ff2018-08-05 12:14:17 -07002324 auto hwcLayer = compositionInfo.hwc.hwcLayer;
2325 if ((displayId >= 0) && hwcLayer) {
2326 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer.get());
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002327 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002328
2329 // If the layer was client composited in the previous frame, we
2330 // need to merge with the previous client target acquire fence.
2331 // Since we do not track that, always merge with the current
2332 // client target acquire fence when it is available, even though
2333 // this is suboptimal.
David Sodman10a41ff2018-08-05 12:14:17 -07002334 if (compositionInfo.compositionType == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002335 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002337 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002338
David Sodman10a41ff2018-08-05 12:14:17 -07002339 if (compositionInfo.layer) {
2340 compositionInfo.layer->onLayerDisplayed(releaseFence);
2341 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002342 }
Chia-I Wu83806892017-11-16 10:50:20 -08002343
2344 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002346 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002348 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002349 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002350 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002351 }
2352 }
2353
Dominik Laskowski7e045462018-05-30 13:02:02 -07002354 if (displayId >= 0) {
2355 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002356 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002357 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358}
2359
Mathias Agopian87baae12012-07-31 12:38:26 -07002360void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002361{
Mathias Agopian841cde52012-03-01 15:44:37 -08002362 ATRACE_CALL();
2363
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002364 // here we keep a copy of the drawing state (that is the state that's
2365 // going to be overwritten by handleTransactionLocked()) outside of
2366 // mStateLock so that the side-effects of the State assignment
2367 // don't happen with mStateLock held (which can cause deadlocks).
2368 State drawingState(mDrawingState);
2369
Mathias Agopianca4d3602011-05-19 15:38:14 -07002370 Mutex::Autolock _l(mStateLock);
2371 const nsecs_t now = systemTime();
2372 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373
Mathias Agopianca4d3602011-05-19 15:38:14 -07002374 // Here we're guaranteed that some transaction flags are set
2375 // so we can call handleTransactionLocked() unconditionally.
2376 // We call getTransactionFlags(), which will also clear the flags,
2377 // with mStateLock held to guarantee that mCurrentState won't change
2378 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002379
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002380 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002381 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002382 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002383
Mathias Agopianca4d3602011-05-19 15:38:14 -07002384 mLastTransactionTime = systemTime() - now;
2385 mDebugInTransaction = 0;
2386 invalidateHwcGeometry();
2387 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002388}
2389
Dominik Laskowski7e045462018-05-30 13:02:02 -07002390DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002392 // Figure out whether the event is for the primary display or an
2393 // external display by matching the Hwc display id against one for a
2394 // connected display. If we did not find a match, we then check what
2395 // displays are not already connected to determine the type. If we don't
2396 // have a connected primary display, we assume the new display is meant to
2397 // be the primary display, and then if we don't have an external display,
2398 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002399 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2400 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002401 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002402 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002403 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002404 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002405 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002406 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002407 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002408 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002409 return DisplayDevice::DISPLAY_EXTERNAL;
2410 }
2411
2412 return DisplayDevice::DISPLAY_ID_INVALID;
2413}
2414
Lloyd Piqueba04e622017-12-14 17:11:26 -08002415void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2416 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002417 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002418 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002419 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002420 continue;
2421 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002422
2423 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2424 ALOGE("External displays are not supported by the vr hardware composer.");
2425 continue;
2426 }
2427
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002428 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002429 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002430 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002431 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002432 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002433
2434 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002435 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002436 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002437 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002438 DisplayDeviceState info;
2439 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002440 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2441 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002442 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002444 mInterceptor->saveDisplayCreation(info);
2445 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002447 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002448
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002449 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002450 if (idx >= 0) {
2451 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002452 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002453 mCurrentState.displays.removeItemsAt(idx);
2454 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002456 }
2457
2458 processDisplayChangesLocked();
2459 }
2460
2461 mPendingHotplugEvents.clear();
2462}
2463
Lloyd Pique99d3da52018-01-22 17:48:03 -08002464sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002465 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002466 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002467 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002468 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002469 HdrCapabilities hdrCapabilities;
2470 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002471
Peiyong Lin13effd12018-07-24 17:01:47 -07002472 if (useColorManagement && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002473 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002475 if (isWideColorMode(colorMode)) {
2476 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002478
Dominik Laskowski7e045462018-05-30 13:02:02 -07002479 std::vector<RenderIntent> renderIntents =
2480 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002481 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002482 }
tangrobin6753a022018-08-10 10:58:54 +08002483 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002484
tangrobin6753a022018-08-10 10:58:54 +08002485 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002486 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2487 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2488 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489
2490 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2491 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2492
2493 /*
2494 * Create our display's surface
2495 */
Peiyong Lin833074a2018-08-28 11:53:54 -07002496 std::unique_ptr<renderengine::Surface> renderSurface = getRenderEngine().createSurface();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002498 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002499 renderSurface->setNativeWindow(nativeWindow.get());
Alec Mouri05483a02018-09-10 21:03:42 +00002500 const int displayWidth = renderSurface->getWidth();
2501 const int displayHeight = renderSurface->getHeight();
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
2503 // Make sure that composition can never be stalled by a virtual display
2504 // consumer that isn't processing buffers fast enough. We have to do this
2505 // in two places:
2506 // * Here, in case the display is composed entirely by HWC.
2507 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2508 // window's swap interval in eglMakeCurrent, so they'll override the
2509 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002510 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002511 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2512 }
2513
Chia-I Wua02871c2018-08-27 14:38:23 -07002514 const int displayInstallOrientation = state.type == DisplayDevice::DISPLAY_PRIMARY ?
2515 primaryDisplayOrientation : DisplayState::eOrientationDefault;
2516
Lloyd Pique99d3da52018-01-22 17:48:03 -08002517 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002518 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002520 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002521 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2522 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
Chia-I Wua02871c2018-08-27 14:38:23 -07002523 displayHeight, displayInstallOrientation, hasWideColorGamut,
2524 hdrCapabilities, supportedPerFrameMetadata, hwcColorModes,
2525 initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526
2527 if (maxFrameBufferAcquiredBuffers >= 3) {
2528 nativeWindowSurface->preallocateBuffers();
2529 }
2530
2531 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002532 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2533 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002534 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002535 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002536 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002537 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002538 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002539 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002540 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002541 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 display->setLayerStack(state.layerStack);
2543 display->setProjection(state.orientation, state.viewport, state.frame);
2544 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002545
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002546 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002547}
2548
Lloyd Pique347200f2017-12-14 17:00:15 -08002549void SurfaceFlinger::processDisplayChangesLocked() {
2550 // here we take advantage of Vector's copy-on-write semantics to
2551 // improve performance by skipping the transaction entirely when
2552 // know that the lists are identical
2553 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2554 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2555 if (!curr.isIdenticalTo(draw)) {
2556 mVisibleRegionsDirty = true;
2557 const size_t cc = curr.size();
2558 size_t dc = draw.size();
2559
2560 // find the displays that were removed
2561 // (ie: in drawing state but not in current state)
2562 // also handle displays that changed
2563 // (ie: displays that are in both lists)
2564 for (size_t i = 0; i < dc;) {
2565 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2566 if (j < 0) {
2567 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002568 // Call makeCurrent() on the primary display so we can
2569 // be sure that nothing associated with this display
2570 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002571 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2572 defaultDisplay->makeCurrent();
2573 }
2574 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2575 display->disconnect(getHwComposer());
2576 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002577 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002578 if (mUseScheduler) {
2579 mScheduler->hotplugReceived(mAppConnectionHandle,
2580 EventThread::DisplayType::Primary, false);
2581 } else {
2582 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2583 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002584 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002585 if (mUseScheduler) {
2586 mScheduler->hotplugReceived(mAppConnectionHandle,
2587 EventThread::DisplayType::External, false);
2588 } else {
2589 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2590 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002591 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002592 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002593 } else {
2594 // this display is in both lists. see if something changed.
2595 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002596 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2598 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2599 if (state_binder != draw_binder) {
2600 // changing the surface is like destroying and
2601 // recreating the DisplayDevice, so we just remove it
2602 // from the drawing state, so that it get re-added
2603 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002604 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2605 display->disconnect(getHwComposer());
2606 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002607 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002608 mDrawingState.displays.removeItemsAt(i);
2609 dc--;
2610 // at this point we must loop to the next item
2611 continue;
2612 }
2613
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002614 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002615 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002616 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002617 }
2618 if ((state.orientation != draw[i].orientation) ||
2619 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002620 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002621 }
2622 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002623 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002624 }
2625 }
2626 }
2627 ++i;
2628 }
2629
2630 // find displays that were added
2631 // (ie: in current state but not in drawing state)
2632 for (size_t i = 0; i < cc; i++) {
2633 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2634 const DisplayDeviceState& state(curr[i]);
2635
2636 sp<DisplaySurface> dispSurface;
2637 sp<IGraphicBufferProducer> producer;
2638 sp<IGraphicBufferProducer> bqProducer;
2639 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002640 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002641
Dominik Laskowski7e045462018-05-30 13:02:02 -07002642 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002643 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002644 // Virtual displays without a surface are dormant:
2645 // they have external state (layer stack, projection,
2646 // etc.) but no internal state (i.e. a DisplayDevice).
2647 if (state.surface != nullptr) {
2648 // Allow VR composer to use virtual displays.
2649 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2650 int width = 0;
2651 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2652 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2653 int height = 0;
2654 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2655 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2656 int intFormat = 0;
2657 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2658 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002659 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002660
Dominik Laskowski7e045462018-05-30 13:02:02 -07002661 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2662 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002663 }
2664
2665 // TODO: Plumb requested format back up to consumer
2666
2667 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002668 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002669 bqProducer, bqConsumer,
2670 state.displayName);
2671
2672 dispSurface = vds;
2673 producer = vds;
2674 }
2675 } else {
2676 ALOGE_IF(state.surface != nullptr,
2677 "adding a supported display, but rendering "
2678 "surface is provided (%p), ignoring it",
2679 state.surface.get());
2680
Dominik Laskowski7e045462018-05-30 13:02:02 -07002681 displayId = state.type;
2682 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002683 producer = bqProducer;
2684 }
2685
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002686 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002687 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002688 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002689 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002690 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002691 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002692 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002693 if (mUseScheduler) {
2694 mScheduler->hotplugReceived(mAppConnectionHandle,
2695 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002696 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002697 } else {
2698 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2699 true);
2700 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002701 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002702 if (mUseScheduler) {
2703 mScheduler->hotplugReceived(mAppConnectionHandle,
2704 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002705 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002706 } else {
2707 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2708 true);
2709 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002710 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 }
2712 }
2713 }
2714 }
2715 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002716
2717 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002718}
2719
Mathias Agopian87baae12012-07-31 12:38:26 -07002720void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002721{
Dan Stoza7dde5992015-05-22 09:51:44 -07002722 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002723 mCurrentState.traverseInZOrder([](Layer* layer) {
2724 layer->notifyAvailableFrames();
2725 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002726
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 /*
2728 * Traversal of the children
2729 * (perform the transaction for each of them if needed)
2730 */
2731
Mathias Agopian3559b072012-08-15 13:46:03 -07002732 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002733 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002735 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736
2737 const uint32_t flags = layer->doTransaction(0);
2738 if (flags & Layer::eVisibleRegion)
2739 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002740 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 }
2742
2743 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002744 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745 */
2746
Mathias Agopiane57f2922012-08-09 16:29:12 -07002747 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002748 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002749 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002750 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002751
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002752 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002753 // The transform hint might have changed for some layers
2754 // (either because a display has changed, or because a layer
2755 // as changed).
2756 //
2757 // Walk through all the layers in currentLayers,
2758 // and update their transform hint.
2759 //
2760 // If a layer is visible only on a single display, then that
2761 // display is used to calculate the hint, otherwise we use the
2762 // default display.
2763 //
2764 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2765 // the hint is set before we acquire a buffer from the surface texture.
2766 //
2767 // NOTE: layer transactions have taken place already, so we use their
2768 // drawing state. However, SurfaceFlinger's own transaction has not
2769 // happened yet, so we must use the current state layer list
2770 // (soon to become the drawing state list).
2771 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002772 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002773 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002774 bool first = true;
2775 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002776 // NOTE: we rely on the fact that layers are sorted by
2777 // layerStack first (so we don't have to traverse the list
2778 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002779 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002780 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002781 currentlayerStack = layerStack;
2782 // figure out if this layerstack is mirrored
2783 // (more than one display) if so, pick the default display,
2784 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002785 hintDisplay = nullptr;
2786 for (const auto& [token, display] : mDisplays) {
2787 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2788 if (hintDisplay) {
2789 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002790 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002791 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002792 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002793 }
2794 }
2795 }
2796 }
Chet Haase91d25932013-04-11 15:24:55 -07002797
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002798 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002799 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2800 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002801
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002802 // could be null when this layer is using a layerStack
2803 // that is not visible on any display. Also can occur at
2804 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002805 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002806 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002807
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002808 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002809 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002810 if (hintDisplay) {
2811 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002812 }
Robert Carr2047fae2016-11-28 14:09:09 -08002813
2814 first = false;
2815 });
Mathias Agopian84300952012-11-21 16:02:13 -08002816 }
2817
2818
Mathias Agopian3559b072012-08-15 13:46:03 -07002819 /*
2820 * Perform our own transaction if needed
2821 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002822
2823 if (mLayersAdded) {
2824 mLayersAdded = false;
2825 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002826 mVisibleRegionsDirty = true;
2827 }
2828
2829 // some layers might have been removed, so
2830 // we need to update the regions they're exposing.
2831 if (mLayersRemoved) {
2832 mLayersRemoved = false;
2833 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002834 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002836 // this layer is not visible anymore
2837 // TODO: we could traverse the tree from front to back and
2838 // compute the actual visible region
2839 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002840 Region visibleReg;
2841 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002842 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002843 }
Robert Carr2047fae2016-11-28 14:09:09 -08002844 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 }
2846
2847 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002848
2849 updateCursorAsync();
2850}
2851
2852void SurfaceFlinger::updateCursorAsync()
2853{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002855 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002856 continue;
2857 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2860 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002861 }
2862 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863}
2864
2865void SurfaceFlinger::commitTransaction()
2866{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002867 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002868 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002869 for (const auto& l : mLayersPendingRemoval) {
2870 recordBufferingStats(l->getName().string(),
2871 l->getOccupancyHistory(true));
2872 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002873 }
2874 mLayersPendingRemoval.clear();
2875 }
2876
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002877 // If this transaction is part of a window animation then the next frame
2878 // we composite should be considered an animation as well.
2879 mAnimCompositionPending = mAnimTransactionPending;
2880
Mathias Agopian4fec8732012-06-29 14:12:52 -07002881 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002882 // clear the "changed" flags in current state
2883 mCurrentState.colorMatrixChanged = false;
2884
Robert Carr1f0a16a2016-10-24 16:27:39 -07002885 mDrawingState.traverseInZOrder([](Layer* layer) {
2886 layer->commitChildList();
2887 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002888 mTransactionPending = false;
2889 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002890 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002891}
2892
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002893void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2894 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002895 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002896 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002897
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898 Region aboveOpaqueLayers;
2899 Region aboveCoveredLayers;
2900 Region dirty;
2901
Mathias Agopian87baae12012-07-31 12:38:26 -07002902 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903
Robert Carr2047fae2016-11-28 14:09:09 -08002904 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002905 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002906 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002907
Jesse Hall01e29052013-02-19 16:13:35 -08002908 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002909 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002910 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002911 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002912
Mathias Agopianab028732010-03-16 16:41:46 -07002913 /*
2914 * opaqueRegion: area of a surface that is fully opaque.
2915 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002916 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002917
2918 /*
2919 * visibleRegion: area of a surface that is visible on screen
2920 * and not fully transparent. This is essentially the layer's
2921 * footprint minus the opaque regions above it.
2922 * Areas covered by a translucent surface are considered visible.
2923 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002924 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002925
2926 /*
2927 * coveredRegion: area of a surface that is covered by all
2928 * visible regions above it (which includes the translucent areas).
2929 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002930 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002931
Jesse Halla8026d22012-09-25 13:25:04 -07002932 /*
2933 * transparentRegion: area of a surface that is hinted to be completely
2934 * transparent. This is only used to tell when the layer has no visible
2935 * non-transparent regions and can be removed from the layer list. It
2936 * does not affect the visibleRegion of this layer or any layers
2937 * beneath it. The hint may not be correct if apps don't respect the
2938 * SurfaceView restrictions (which, sadly, some don't).
2939 */
2940 Region transparentRegion;
2941
Mathias Agopianab028732010-03-16 16:41:46 -07002942
2943 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002944 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002945 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002946 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002947 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002948 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002949 if (!visibleRegion.isEmpty()) {
2950 // Remove the transparent area from the visible region
2951 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002952 if (tr.preserveRects()) {
2953 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002954 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002955 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002956 // transformation too complex, can't do the
2957 // transparent region optimization.
2958 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002959 }
Mathias Agopianab028732010-03-16 16:41:46 -07002960 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961
Mathias Agopianab028732010-03-16 16:41:46 -07002962 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002963 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002964 if (layer->getAlpha() == 1.0f && !translucent &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002965 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002966 // the opaque region is the layer's footprint
2967 opaqueRegion = visibleRegion;
2968 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969 }
2970 }
2971
Robert Carre5f4f692018-01-12 13:12:28 -08002972 if (visibleRegion.isEmpty()) {
2973 layer->clearVisibilityRegions();
2974 return;
2975 }
2976
Mathias Agopianab028732010-03-16 16:41:46 -07002977 // Clip the covered region to the visible region
2978 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2979
2980 // Update aboveCoveredLayers for next (lower) layer
2981 aboveCoveredLayers.orSelf(visibleRegion);
2982
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 // subtract the opaque region covered by the layers above us
2984 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002985
2986 // compute this layer's dirty region
2987 if (layer->contentDirty) {
2988 // we need to invalidate the whole region
2989 dirty = visibleRegion;
2990 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002991 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002992 layer->contentDirty = false;
2993 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002994 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002995 * the exposed region consists of two components:
2996 * 1) what's VISIBLE now and was COVERED before
2997 * 2) what's EXPOSED now less what was EXPOSED before
2998 *
2999 * note that (1) is conservative, we start with the whole
3000 * visible region but only keep what used to be covered by
3001 * something -- which mean it may have been exposed.
3002 *
3003 * (2) handles areas that were not covered by anything but got
3004 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003005 */
Mathias Agopianab028732010-03-16 16:41:46 -07003006 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003007 const Region oldVisibleRegion = layer->visibleRegion;
3008 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003009 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3010 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011 }
3012 dirty.subtractSelf(aboveOpaqueLayers);
3013
3014 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003015 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003016
Mathias Agopianab028732010-03-16 16:41:46 -07003017 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003019
Jesse Halla8026d22012-09-25 13:25:04 -07003020 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003021 layer->setVisibleRegion(visibleRegion);
3022 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003023 layer->setVisibleNonTransparentRegion(
3024 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003025 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003026
Mathias Agopian87baae12012-07-31 12:38:26 -07003027 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003028}
3029
Chia-I Wuab0c3192017-08-01 11:29:00 -07003030void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003031 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003032 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3033 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003034 }
3035 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003036}
3037
Dan Stoza6b9454d2014-11-07 16:00:59 -08003038bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003040 ALOGV("handlePageFlip");
3041
Brian Andersond6927fb2016-07-23 23:37:30 -07003042 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003043
Mathias Agopian4fec8732012-06-29 14:12:52 -07003044 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003045 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003046 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003047
3048 // Store the set of layers that need updates. This set must not change as
3049 // buffers are being latched, as this could result in a deadlock.
3050 // Example: Two producers share the same command stream and:
3051 // 1.) Layer 0 is latched
3052 // 2.) Layer 0 gets a new frame
3053 // 2.) Layer 1 gets a new frame
3054 // 3.) Layer 1 is latched.
3055 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3056 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003057 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003058 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003059 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003060 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003061 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003062 } else {
3063 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003064 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003065 } else {
3066 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003067 }
Robert Carr2047fae2016-11-28 14:09:09 -08003068 });
3069
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003071 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003072 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003073 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003074 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003075 newDataLatched = true;
3076 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003078
Alec Mouri86770e52018-09-24 22:40:58 +00003079 // Clear the renderengine fence here...
3080 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3081 // clear instead of sp::clear.
3082 getBE().flushFence = Fence::NO_FENCE;
3083
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003084 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003085
3086 // If we will need to wake up at some time in the future to deal with a
3087 // queued frame that shouldn't be displayed during this vsync period, wake
3088 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003089 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003090 signalLayerUpdate();
3091 }
3092
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003093 // enter boot animation on first buffer latch
3094 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3095 ALOGI("Enter boot animation");
3096 mBootStage = BootStage::BOOTANIMATION;
3097 }
3098
Dan Stoza6b9454d2014-11-07 16:00:59 -08003099 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003100 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003101}
3102
Mathias Agopianad456f92011-01-13 17:53:01 -08003103void SurfaceFlinger::invalidateHwcGeometry()
3104{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003105 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003106}
3107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003108void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
3109 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003110 // We only need to actually compose the display if:
3111 // 1) It is being handled by hardware composer, which may need this to
3112 // keep its virtual display state machine in sync, or
3113 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07003114 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08003115 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003116 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003117 return;
3118 }
3119
Dan Stoza9e56aa02015-11-02 13:00:03 -08003120 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003121 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003122
3123 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003124 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125}
3126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003127bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003128 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003129
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003130 const Region bounds(display->bounds());
3131 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003132 const auto displayId = display->getId();
3133 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003134 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003135
Chia-I Wu8e50e692018-05-04 10:12:37 -07003136 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08003137 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003138
Dan Stoza9e56aa02015-11-02 13:00:03 -08003139 if (hasClientComposition) {
3140 ALOGV("hasClientComposition");
3141
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003142 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003143 if (display->hasWideColorGamut()) {
3144 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003145 }
3146 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003147 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003148 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003149
Dominik Laskowski7e045462018-05-30 13:02:02 -07003150 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003151 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
3152 HWC2::Capability::SkipClientColorTransform);
3153
Chia-I Wud49d6692018-06-27 07:17:41 +08003154 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003155 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3156 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003157 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003158 }
3159
Chia-I Wud49d6692018-06-27 07:17:41 +08003160 // The current enhanced saturation matrix is designed to enhance Display P3,
3161 // thus we only apply this matrix when the render intent is not colorimetric
3162 // and the output color space is Display P3.
3163 needsEnhancedColorMatrix =
3164 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
3165 outputDataspace == Dataspace::DISPLAY_P3);
3166 if (needsEnhancedColorMatrix) {
3167 colorMatrix *= mEnhancedSaturationMatrix;
3168 }
3169
3170 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003171
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003172 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08003173 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003174 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08003175 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07003176
3177 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003178 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
3179 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
3180 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07003181 }
3182 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003183 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003184
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003185 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003186 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003187 // when using overlays, we assume a fully transparent framebuffer
3188 // NOTE: we could reduce how much we need to clear, for instance
3189 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003190 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003191 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003192 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003193 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003194 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003195 // we're left with the letterbox region
3196 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003197 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003198
3199 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003200 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003201
Mathias Agopianb9494d52012-04-18 02:28:45 -07003202 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003203 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003204 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003205 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003206 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003207 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003208
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003209 const Rect& bounds = display->getBounds();
3210 const Rect& scissor = display->getScissor();
3211 if (scissor != bounds) {
3212 // scissor doesn't match the screen's dimensions, so we
3213 // need to clear everything outside of it and enable
3214 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003215
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003216 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003217 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003218 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003219 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003220
Mathias Agopian85d751c2012-08-29 16:59:24 -07003221 /*
3222 * and then, render the layers targeted at the framebuffer
3223 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003224
Dan Stoza9e56aa02015-11-02 13:00:03 -08003225 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003226 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003227 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003228 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003229 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003230 displayTransform.transform(layer->visibleRegion)));
3231 ALOGV("Layer: %s", layer->getName().string());
3232 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003233 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003234 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003235 case HWC2::Composition::Cursor:
3236 case HWC2::Composition::Device:
3237 case HWC2::Composition::Sideband:
3238 case HWC2::Composition::SolidColor: {
David Sodmanc1498e62018-09-12 14:36:26 -07003239 const Layer::State& state(layer->getDrawingState());
3240 if (layer->getClearClientTarget(displayId) && !firstLayer &&
3241 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3242 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003243 // never clear the very first layer since we're
3244 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003245 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003246 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003247 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003248 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003249 case HWC2::Composition::Client: {
David Sodmanc1498e62018-09-12 14:36:26 -07003250 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003251 break;
3252 }
3253 default:
3254 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003255 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003256 } else {
3257 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003258 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003259 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003260 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003261
Chia-I Wud49d6692018-06-27 07:17:41 +08003262 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003263 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003264 }
3265
Mathias Agopianf45c5102012-10-24 16:29:17 -07003266 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003267 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003268 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269}
3270
Chia-I Wu28e3a252018-09-07 12:05:02 -07003271void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003272 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003273 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274}
3275
Dan Stoza7d89d062015-04-30 13:29:25 -07003276status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003277 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003278 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003279 const sp<Layer>& lbc,
3280 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003281{
Dan Stoza7d89d062015-04-30 13:29:25 -07003282 // add this layer to the current state list
3283 {
3284 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003285 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003286 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3287 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003288 return NO_MEMORY;
3289 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003290 if (parent == nullptr) {
3291 mCurrentState.layersSortedByZ.add(lbc);
3292 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003293 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003294 ALOGE("addClientLayer called with a removed parent");
3295 return NAME_NOT_FOUND;
3296 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003297 parent->addChild(lbc);
3298 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003299
Yiwei Zhang243b3782018-05-15 17:40:04 -07003300 if (gbc != nullptr) {
3301 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3302 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3303 mMaxGraphicBufferProducerListSize,
3304 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3305 mGraphicBufferProducerList.size(),
3306 mMaxGraphicBufferProducerListSize, mNumLayers);
3307 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003308 mLayersAdded = true;
3309 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003310 }
3311
Mathias Agopian96f08192010-06-02 23:28:45 -07003312 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003313 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003314
Dan Stoza7d89d062015-04-30 13:29:25 -07003315 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003316}
3317
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003318status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003319 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003320 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3321}
Robert Carr7f9b8992017-03-10 11:08:39 -08003322
chaviwca27f252018-02-06 16:46:39 -08003323status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3324 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003325 if (layer->isPendingRemoval()) {
3326 return NO_ERROR;
3327 }
3328
Robert Carr1f0a16a2016-10-24 16:27:39 -07003329 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003330 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003331 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003332 if (topLevelOnly) {
3333 return NO_ERROR;
3334 }
3335
Chia-I Wu98f1c102017-05-30 14:54:08 -07003336 sp<Layer> ancestor = p;
3337 while (ancestor->getParent() != nullptr) {
3338 ancestor = ancestor->getParent();
3339 }
3340 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3341 ALOGE("removeLayer called with a layer whose parent has been removed");
3342 return NAME_NOT_FOUND;
3343 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003344
3345 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003346 } else {
3347 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003348 }
3349
Robert Carr136e2f62017-02-08 17:54:29 -08003350 // As a matter of normal operation, the LayerCleaner will produce a second
3351 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3352 // so we will succeed in promoting it, but it's already been removed
3353 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3354 // otherwise something has gone wrong and we are leaking the layer.
3355 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003356 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3357 layer->getName().string(),
3358 (p != nullptr) ? p->getName().string() : "no-parent");
3359 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003360 } else if (index < 0) {
3361 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003362 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003363
Chia-I Wuc6657022017-08-15 11:18:17 -07003364 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003365 mLayersPendingRemoval.add(layer);
3366 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003367 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003368 setTransactionFlags(eTransactionNeeded);
3369 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003370}
3371
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003372uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003373 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003374}
3375
Mathias Agopian3f844832013-08-07 21:24:32 -07003376uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003377 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003378}
3379
Mathias Agopian3f844832013-08-07 21:24:32 -07003380uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003381 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3382}
3383
3384uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3385 VSyncModulator::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003386 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003387 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003388 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003389 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003390 }
3391 return old;
3392}
3393
chaviwca27f252018-02-06 16:46:39 -08003394bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3395 for (const ComposerState& state : states) {
3396 // Here we need to check that the interface we're given is indeed
3397 // one of our own. A malicious client could give us a nullptr
3398 // IInterface, or one of its own or even one of our own but a
3399 // different type. All these situations would cause us to crash.
3400 if (state.client == nullptr) {
3401 return true;
3402 }
3403
3404 sp<IBinder> binder = IInterface::asBinder(state.client);
3405 if (binder == nullptr) {
3406 return true;
3407 }
3408
3409 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3410 return true;
3411 }
3412 }
3413 return false;
3414}
3415
Mathias Agopian8b33f032012-07-24 20:43:54 -07003416void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003417 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003418 const Vector<DisplayState>& displays,
3419 uint32_t flags)
3420{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003421 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003422 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003423 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003424
chaviwca27f252018-02-06 16:46:39 -08003425 if (containsAnyInvalidClientState(states)) {
3426 return;
3427 }
3428
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003429 if (flags & eAnimation) {
3430 // For window updates that are part of an animation we must wait for
3431 // previous animation "frames" to be handled.
3432 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003433 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003434 if (CC_UNLIKELY(err != NO_ERROR)) {
3435 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003436 // caller after a few seconds.
3437 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3438 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003439 mAnimTransactionPending = false;
3440 break;
3441 }
3442 }
3443 }
3444
chaviwca27f252018-02-06 16:46:39 -08003445 for (const DisplayState& display : displays) {
3446 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003447 }
3448
chaviwca27f252018-02-06 16:46:39 -08003449 for (const ComposerState& state : states) {
3450 transactionFlags |= setClientStateLocked(state);
3451 }
3452
3453 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3454 // as destroyed should only occur after setting all other states. This is to allow for a
3455 // child re-parent to happen before marking its original parent as destroyed (which would
3456 // then mark the child as destroyed).
3457 for (const ComposerState& state : states) {
3458 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003459 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003460
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003461 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3462 // anyway. This can be used as a flush mechanism for previous async transactions.
3463 // Empty animation transaction can be used to simulate back-pressure, so also force a
3464 // transaction for empty animation transactions.
3465 if (transactionFlags == 0 &&
3466 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003467 transactionFlags = eTransactionNeeded;
3468 }
3469
Mathias Agopian386aa982011-11-07 21:58:03 -08003470 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003471 if (mInterceptor->isEnabled()) {
3472 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003473 }
Irvel468051e2016-06-13 16:44:44 -07003474
Mathias Agopian386aa982011-11-07 21:58:03 -08003475 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003476 const auto start = (flags & eEarlyWakeup)
3477 ? VSyncModulator::TransactionStart::EARLY
3478 : VSyncModulator::TransactionStart::NORMAL;
3479 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003480
3481 // if this is a synchronous transaction, wait for it to take effect
3482 // before returning.
3483 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003484 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003485 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003486 if (flags & eAnimation) {
3487 mAnimTransactionPending = true;
3488 }
3489 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003490 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3491 if (CC_UNLIKELY(err != NO_ERROR)) {
3492 // just in case something goes wrong in SF, return to the
3493 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003494 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3495 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003496 break;
3497 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003498 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499 }
3500}
3501
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003502uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3503 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3504 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003505
Mathias Agopiane57f2922012-08-09 16:29:12 -07003506 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003507 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3508
3509 const uint32_t what = s.what;
3510 if (what & DisplayState::eSurfaceChanged) {
3511 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3512 state.surface = s.surface;
3513 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003514 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003515 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003516 if (what & DisplayState::eLayerStackChanged) {
3517 if (state.layerStack != s.layerStack) {
3518 state.layerStack = s.layerStack;
3519 flags |= eDisplayTransactionNeeded;
3520 }
3521 }
3522 if (what & DisplayState::eDisplayProjectionChanged) {
3523 if (state.orientation != s.orientation) {
3524 state.orientation = s.orientation;
3525 flags |= eDisplayTransactionNeeded;
3526 }
3527 if (state.frame != s.frame) {
3528 state.frame = s.frame;
3529 flags |= eDisplayTransactionNeeded;
3530 }
3531 if (state.viewport != s.viewport) {
3532 state.viewport = s.viewport;
3533 flags |= eDisplayTransactionNeeded;
3534 }
3535 }
3536 if (what & DisplayState::eDisplaySizeChanged) {
3537 if (state.width != s.width) {
3538 state.width = s.width;
3539 flags |= eDisplayTransactionNeeded;
3540 }
3541 if (state.height != s.height) {
3542 state.height = s.height;
3543 flags |= eDisplayTransactionNeeded;
3544 }
3545 }
3546
Mathias Agopiane57f2922012-08-09 16:29:12 -07003547 return flags;
3548}
3549
Robert Carrd4ae7f32018-06-07 16:10:57 -07003550bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3551 IPCThreadState* ipc = IPCThreadState::self();
3552 const int pid = ipc->getCallingPid();
3553 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003554 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003555 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003556 return false;
3557 }
3558 return true;
3559}
3560
chaviwca27f252018-02-06 16:46:39 -08003561uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3562 const layer_state_t& s = composerState.state;
3563 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3564
Mathias Agopian13127d82013-03-05 17:47:11 -08003565 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003566 if (layer == nullptr) {
3567 return 0;
3568 }
3569
3570 if (layer->isPendingRemoval()) {
3571 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3572 return 0;
3573 }
3574
3575 uint32_t flags = 0;
3576
3577 const uint32_t what = s.what;
3578 bool geometryAppliesWithResize =
3579 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003580
3581 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3582 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003583 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003584 layer->pushPendingState();
3585 }
3586
chaviw8b3871a2017-11-01 17:41:01 -07003587 if (what & layer_state_t::ePositionChanged) {
3588 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3589 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003590 }
chaviw8b3871a2017-11-01 17:41:01 -07003591 }
3592 if (what & layer_state_t::eLayerChanged) {
3593 // NOTE: index needs to be calculated before we update the state
3594 const auto& p = layer->getParent();
3595 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003596 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003597 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003598 mCurrentState.layersSortedByZ.removeAt(idx);
3599 mCurrentState.layersSortedByZ.add(layer);
3600 // we need traversal (state changed)
3601 // AND transaction (list changed)
3602 flags |= eTransactionNeeded|eTraversalNeeded;
3603 }
chaviw8b3871a2017-11-01 17:41:01 -07003604 } else {
3605 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003606 flags |= eTransactionNeeded|eTraversalNeeded;
3607 }
3608 }
chaviw8b3871a2017-11-01 17:41:01 -07003609 }
3610 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003611 // NOTE: index needs to be calculated before we update the state
3612 const auto& p = layer->getParent();
3613 if (p == nullptr) {
3614 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3615 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3616 mCurrentState.layersSortedByZ.removeAt(idx);
3617 mCurrentState.layersSortedByZ.add(layer);
3618 // we need traversal (state changed)
3619 // AND transaction (list changed)
3620 flags |= eTransactionNeeded|eTraversalNeeded;
3621 }
3622 } else {
3623 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3624 flags |= eTransactionNeeded|eTraversalNeeded;
3625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 }
3627 }
3628 if (what & layer_state_t::eSizeChanged) {
3629 if (layer->setSize(s.w, s.h)) {
3630 flags |= eTraversalNeeded;
3631 }
3632 }
3633 if (what & layer_state_t::eAlphaChanged) {
3634 if (layer->setAlpha(s.alpha))
3635 flags |= eTraversalNeeded;
3636 }
3637 if (what & layer_state_t::eColorChanged) {
3638 if (layer->setColor(s.color))
3639 flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003642 // TODO: b/109894387
3643 //
3644 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3645 // rotation. To see the problem observe that if we have a square parent, and a child
3646 // of the same size, then we rotate the child 45 degrees around it's center, the child
3647 // must now be cropped to a non rectangular 8 sided region.
3648 //
3649 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3650 // private API, and the WindowManager only uses rotation in one case, which is on a top
3651 // level layer in which cropping is not an issue.
3652 //
3653 // However given that abuse of rotation matrices could lead to surfaces extending outside
3654 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3655 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3656 // transformations.
3657 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003658 flags |= eTraversalNeeded;
3659 }
3660 if (what & layer_state_t::eTransparentRegionChanged) {
3661 if (layer->setTransparentRegionHint(s.transparentRegion))
3662 flags |= eTraversalNeeded;
3663 }
3664 if (what & layer_state_t::eFlagsChanged) {
3665 if (layer->setFlags(s.flags, s.mask))
3666 flags |= eTraversalNeeded;
3667 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003668 if (what & layer_state_t::eCropChanged_legacy) {
3669 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003670 flags |= eTraversalNeeded;
3671 }
chaviw8b3871a2017-11-01 17:41:01 -07003672 if (what & layer_state_t::eLayerStackChanged) {
3673 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3674 // We only allow setting layer stacks for top level layers,
3675 // everything else inherits layer stack from its parent.
3676 if (layer->hasParent()) {
3677 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3678 layer->getName().string());
3679 } else if (idx < 0) {
3680 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3681 "that also does not appear in the top level layer list. Something"
3682 " has gone wrong.", layer->getName().string());
3683 } else if (layer->setLayerStack(s.layerStack)) {
3684 mCurrentState.layersSortedByZ.removeAt(idx);
3685 mCurrentState.layersSortedByZ.add(layer);
3686 // we need traversal (state changed)
3687 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003688 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003689 }
3690 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003691 if (what & layer_state_t::eDeferTransaction_legacy) {
3692 if (s.barrierHandle_legacy != nullptr) {
3693 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3694 } else if (s.barrierGbp_legacy != nullptr) {
3695 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003696 if (authenticateSurfaceTextureLocked(gbp)) {
3697 const auto& otherLayer =
3698 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003699 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003700 } else {
3701 ALOGE("Attempt to defer transaction to to an"
3702 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003703 }
3704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 // We don't trigger a traversal here because if no other state is
3706 // changed, we don't want this to cause any more work
3707 }
3708 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003709 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003710 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003711 if (!hadParent) {
3712 mCurrentState.layersSortedByZ.remove(layer);
3713 }
chaviw8b3871a2017-11-01 17:41:01 -07003714 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003715 }
chaviw8b3871a2017-11-01 17:41:01 -07003716 }
3717 if (what & layer_state_t::eReparentChildren) {
3718 if (layer->reparentChildren(s.reparentHandle)) {
3719 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003720 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003721 }
chaviw8b3871a2017-11-01 17:41:01 -07003722 if (what & layer_state_t::eDetachChildren) {
3723 layer->detachChildren();
3724 }
3725 if (what & layer_state_t::eOverrideScalingModeChanged) {
3726 layer->setOverrideScalingMode(s.overrideScalingMode);
3727 // We don't trigger a traversal here because if no other state is
3728 // changed, we don't want this to cause any more work
3729 }
Marissa Wall61c58622018-07-18 10:12:20 -07003730 if (what & layer_state_t::eTransformChanged) {
3731 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3732 }
3733 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3734 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3735 flags |= eTraversalNeeded;
3736 }
3737 if (what & layer_state_t::eCropChanged) {
3738 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3739 }
3740 if (what & layer_state_t::eBufferChanged) {
3741 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3742 }
3743 if (what & layer_state_t::eAcquireFenceChanged) {
3744 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3745 }
3746 if (what & layer_state_t::eDataspaceChanged) {
3747 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3748 }
3749 if (what & layer_state_t::eHdrMetadataChanged) {
3750 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3751 }
3752 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3753 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3754 }
3755 if (what & layer_state_t::eApiChanged) {
3756 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3757 }
3758 if (what & layer_state_t::eSidebandStreamChanged) {
3759 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3760 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003761 return flags;
3762}
3763
chaviwca27f252018-02-06 16:46:39 -08003764void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3765 const layer_state_t& state = composerState.state;
3766 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3767
3768 sp<Layer> layer(client->getLayerUser(state.surface));
3769 if (layer == nullptr) {
3770 return;
3771 }
3772
3773 if (layer->isPendingRemoval()) {
3774 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3775 return;
3776 }
3777
3778 if (state.what & layer_state_t::eDestroySurface) {
3779 removeLayerLocked(mStateLock, layer);
3780 }
3781}
3782
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003783status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003784 const String8& name,
3785 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003786 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003787 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003788 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003789{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003790 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003791 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003792 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003793 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003794 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003795
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003796 status_t result = NO_ERROR;
3797
3798 sp<Layer> layer;
3799
Cody Northropbc755282017-03-31 12:00:08 -06003800 String8 uniqueName = getUniqueLayerName(name);
3801
Mathias Agopian3165cc22012-08-08 19:42:09 -07003802 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003803 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003804 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3805 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003806
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003807 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003808 case ISurfaceComposerClient::eFXSurfaceBufferState:
3809 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3810 break;
chaviw13fdc492017-06-27 12:40:18 -07003811 case ISurfaceComposerClient::eFXSurfaceColor:
3812 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003813 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003814 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003815 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003816 case ISurfaceComposerClient::eFXSurfaceContainer:
3817 result = createContainerLayer(client,
3818 uniqueName, w, h, flags,
3819 handle, &layer);
3820 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003821 default:
3822 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 break;
3824 }
3825
Dan Stoza7d89d062015-04-30 13:29:25 -07003826 if (result != NO_ERROR) {
3827 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003829
Chia-I Wuab0c3192017-08-01 11:29:00 -07003830 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3831 // TODO b/64227542
3832 if (windowType == 441731) {
3833 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3834 layer->setPrimaryDisplayOnly();
3835 }
3836
Albert Chaulk479c60c2017-01-27 14:21:34 -05003837 layer->setInfo(windowType, ownerUid);
3838
Robert Carr1f0a16a2016-10-24 16:27:39 -07003839 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003840 if (result != NO_ERROR) {
3841 return result;
3842 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003843 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003844
3845 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003846 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003847}
3848
Cody Northropbc755282017-03-31 12:00:08 -06003849String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3850{
3851 bool matchFound = true;
3852 uint32_t dupeCounter = 0;
3853
3854 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3855 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3856
Dan Stoza436ccf32018-06-21 12:10:12 -07003857 // Grab the state lock since we're accessing mCurrentState
3858 Mutex::Autolock lock(mStateLock);
3859
Cody Northropbc755282017-03-31 12:00:08 -06003860 // Loop over layers until we're sure there is no matching name
3861 while (matchFound) {
3862 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003863 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003864 if (layer->getName() == uniqueName) {
3865 matchFound = true;
3866 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3867 }
3868 });
3869 }
3870
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003871 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3872 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003873
3874 return uniqueName;
3875}
3876
Marissa Wallfd668622018-05-10 10:21:13 -07003877status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3878 uint32_t w, uint32_t h, uint32_t flags,
3879 PixelFormat& format, sp<IBinder>* handle,
3880 sp<IGraphicBufferProducer>* gbp,
3881 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003882 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003883 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003884 case PIXEL_FORMAT_TRANSPARENT:
3885 case PIXEL_FORMAT_TRANSLUCENT:
3886 format = PIXEL_FORMAT_RGBA_8888;
3887 break;
3888 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003889 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003890 break;
3891 }
3892
Marissa Wallfd668622018-05-10 10:21:13 -07003893 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3894 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003895 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003896 *handle = layer->getHandle();
3897 *gbp = layer->getProducer();
3898 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003900
Marissa Wallfd668622018-05-10 10:21:13 -07003901 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003902 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903}
3904
Marissa Wall61c58622018-07-18 10:12:20 -07003905status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3906 uint32_t w, uint32_t h, uint32_t flags,
3907 sp<IBinder>* handle, sp<Layer>* outLayer) {
3908 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3909 *handle = layer->getHandle();
3910 *outLayer = layer;
3911
3912 return NO_ERROR;
3913}
3914
chaviw13fdc492017-06-27 12:40:18 -07003915status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003916 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003917 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918{
chaviw13fdc492017-06-27 12:40:18 -07003919 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003920 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003921 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003922}
3923
Robert Carr6b3f6c52018-08-13 13:05:17 -07003924status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3925 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3926 sp<IBinder>* handle, sp<Layer>* outLayer)
3927{
3928 *outLayer = new ContainerLayer(this, client, name, w, h, flags);
3929 *handle = (*outLayer)->getHandle();
3930 return NO_ERROR;
3931}
3932
3933
Mathias Agopianac9fa422013-02-11 16:40:36 -08003934status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003935{
Robert Carr9524cb32017-02-13 11:32:32 -08003936 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003937 status_t err = NO_ERROR;
3938 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003939 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003940 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003941 err = removeLayer(l);
3942 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3943 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003944 }
3945 return err;
3946}
3947
Mathias Agopian13127d82013-03-05 17:47:11 -08003948status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003949{
Mathias Agopian67106042013-03-14 19:18:13 -07003950 // called by ~LayerCleaner() when all references to the IBinder (handle)
3951 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003952 sp<Layer> l = layer.promote();
3953 if (l == nullptr) {
3954 // The layer has already been removed, carry on
3955 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003956 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003957 // If we have a parent, then we can continue to live as long as it does.
3958 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003959}
3960
Mathias Agopianb60314a2012-04-10 22:09:54 -07003961// ---------------------------------------------------------------------------
3962
Andy McFadden13a082e2012-08-24 10:16:42 -07003963void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003964 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3965 if (!displayToken) return;
3966
Jesse Hall01e29052013-02-19 16:13:35 -08003967 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003968 Vector<ComposerState> state;
3969 Vector<DisplayState> displays;
3970 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003971 d.what = DisplayState::eDisplayProjectionChanged |
3972 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003973 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003974 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003975 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003976 d.frame.makeInvalid();
3977 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003978 d.width = 0;
3979 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003980 displays.add(d);
3981 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003982
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003983 const auto display = getDisplayDevice(displayToken);
3984 if (!display) return;
3985
3986 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3987
3988 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003989 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003990 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003991
Brian Andersond0010582017-03-07 13:20:31 -08003992 // Use phase of 0 since phase is not known.
3993 // Use latency of 0, which will snap to the ideal latency.
3994 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003995}
3996
3997void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003998 // Async since we may be called from the main thread.
3999 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004000}
4001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004002void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
4003 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004004 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004005 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07004006
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004007 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004008 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004009 return;
4010 }
4011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004012 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004013 ALOGW("Trying to set power mode for virtual display");
4014 return;
4015 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004017 display->setPowerMode(mode);
4018
Lloyd Pique4dccc412018-01-22 17:21:36 -08004019 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07004020 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004021 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07004022 if (idx < 0) {
4023 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
4024 return;
4025 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07004026 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07004027 }
4028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004029 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004030 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004031 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004032 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004033 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004034 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004035 if (mUseScheduler) {
4036 mScheduler->onScreenAcquired(mAppConnectionHandle);
4037 } else {
4038 mEventThread->onScreenAcquired();
4039 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004040 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004041 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004042
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004043 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004044 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004045 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004046
4047 struct sched_param param = {0};
4048 param.sched_priority = 1;
4049 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4050 ALOGW("Couldn't set SCHED_FIFO on display on");
4051 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004052 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004053 // Turn off the display
4054 struct sched_param param = {0};
4055 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4056 ALOGW("Couldn't set SCHED_OTHER on display off");
4057 }
4058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004059 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07004060 disableHardwareVsync(true); // also cancels any in-progress resync
4061
Mathias Agopiancde87a32012-09-13 14:09:01 -07004062 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004063 if (mUseScheduler) {
4064 mScheduler->onScreenReleased(mAppConnectionHandle);
4065 } else {
4066 mEventThread->onScreenReleased();
4067 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004068 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004069
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004070 getHwComposer().setPowerMode(type, mode);
4071 mVisibleRegionsDirty = true;
4072 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004073 } else if (mode == HWC_POWER_MODE_DOZE ||
4074 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004075 // Update display while dozing
4076 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004077 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004078 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004079 if (mUseScheduler) {
4080 mScheduler->onScreenAcquired(mAppConnectionHandle);
4081 } else {
4082 mEventThread->onScreenAcquired();
4083 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004084 resyncToHardwareVsync(true);
4085 }
4086 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4087 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004088 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004089 disableHardwareVsync(true); // also cancels any in-progress resync
4090 // FIXME: eventthread only knows about the main display right now
Ana Krulec98b5b242018-08-10 15:03:23 -07004091 if (mUseScheduler) {
4092 mScheduler->onScreenReleased(mAppConnectionHandle);
4093 } else {
4094 mEventThread->onScreenReleased();
4095 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004096 }
4097 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004098 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004099 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004100 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102
4103 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004104}
4105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004106void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004107 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004108 const auto display = getDisplayDevice(displayToken);
4109 if (!display) {
4110 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4111 displayToken.get());
4112 } else if (display->isVirtual()) {
4113 ALOGW("Attempt to set power mode %d for virtual display", mode);
4114 } else {
4115 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004116 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004117 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004118}
4119
4120// ---------------------------------------------------------------------------
4121
Lloyd Pique755e3192018-01-31 16:46:15 -08004122status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4123 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004125
Mathias Agopianbd115332013-04-18 16:41:04 -07004126 IPCThreadState* ipc = IPCThreadState::self();
4127 const int pid = ipc->getCallingPid();
4128 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004129
Mathias Agopianbd115332013-04-18 16:41:04 -07004130 if ((uid != AID_SHELL) &&
4131 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004132 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07004133 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004134 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004135 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004136 // (this would indicate SF is stuck, but we want to be able to
4137 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004138 status_t err = mStateLock.timedLock(s2ns(1));
4139 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004140 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004141 result.appendFormat(
4142 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
4143 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004144 }
4145
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004146 bool dumpAll = true;
4147 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004148 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004149
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004150 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004151 if ((index < numArgs) &&
4152 (args[index] == String16("--list"))) {
4153 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004154 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004155 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004156 }
4157
4158 if ((index < numArgs) &&
4159 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004160 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004161 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004162 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004163 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004164
4165 if ((index < numArgs) &&
4166 (args[index] == String16("--latency-clear"))) {
4167 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004168 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004169 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004170 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004171
4172 if ((index < numArgs) &&
4173 (args[index] == String16("--dispsync"))) {
4174 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004175 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004176 dumpAll = false;
4177 }
Dan Stozab90cf072015-03-05 11:05:59 -08004178
4179 if ((index < numArgs) &&
4180 (args[index] == String16("--static-screen"))) {
4181 index++;
4182 dumpStaticScreenStats(result);
4183 dumpAll = false;
4184 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004185
4186 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004187 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004188 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004189 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004190 dumpAll = false;
4191 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004192
4193 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4194 index++;
4195 dumpWideColorInfo(result);
4196 dumpAll = false;
4197 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004198
4199 if ((index < numArgs) &&
4200 (args[index] == String16("--enable-layer-stats"))) {
4201 index++;
4202 mLayerStats.enable();
4203 dumpAll = false;
4204 }
4205
4206 if ((index < numArgs) &&
4207 (args[index] == String16("--disable-layer-stats"))) {
4208 index++;
4209 mLayerStats.disable();
4210 dumpAll = false;
4211 }
4212
4213 if ((index < numArgs) &&
4214 (args[index] == String16("--clear-layer-stats"))) {
4215 index++;
4216 mLayerStats.clear();
4217 dumpAll = false;
4218 }
4219
4220 if ((index < numArgs) &&
4221 (args[index] == String16("--dump-layer-stats"))) {
4222 index++;
4223 mLayerStats.dump(result);
4224 dumpAll = false;
4225 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004226
4227 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004228 (args[index] == String16("--frame-composition"))) {
4229 index++;
4230 dumpFrameCompositionInfo(result);
4231 dumpAll = false;
4232 }
4233
4234 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004235 (args[index] == String16("--display-identification"))) {
4236 index++;
4237 dumpDisplayIdentificationData(result);
4238 dumpAll = false;
4239 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004240
4241 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4242 index++;
4243 mTimeStats.parseArgs(asProto, args, index, result);
4244 dumpAll = false;
4245 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004247
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004249 if (asProto) {
4250 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4251 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4252 } else {
4253 dumpAllLocked(args, index, result);
4254 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004255 }
4256
Mathias Agopian9795c422009-08-26 16:36:26 -07004257 if (locked) {
4258 mStateLock.unlock();
4259 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004260 }
4261 write(fd, result.string(), result.size());
4262 return NO_ERROR;
4263}
4264
Dan Stozac7014012014-02-14 15:03:43 -08004265void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4266 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004267{
Robert Carr2047fae2016-11-28 14:09:09 -08004268 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004269 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004270 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004271}
4272
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004273void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004274 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004275{
4276 String8 name;
4277 if (index < args.size()) {
4278 name = String8(args[index]);
4279 index++;
4280 }
4281
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004282 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4283 getHwComposer().isConnected(displayId)) {
4284 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4285 const nsecs_t period = activeConfig->getVsyncPeriod();
4286 result.appendFormat("%" PRId64 "\n", period);
4287 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004288
4289 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004290 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004291 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004292 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004293 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004294 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004295 }
Robert Carr2047fae2016-11-28 14:09:09 -08004296 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297 }
4298}
4299
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004300void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004301 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004302{
4303 String8 name;
4304 if (index < args.size()) {
4305 name = String8(args[index]);
4306 index++;
4307 }
4308
Robert Carr2047fae2016-11-28 14:09:09 -08004309 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004310 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004311 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004312 }
Robert Carr2047fae2016-11-28 14:09:09 -08004313 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004314
Svetoslavd85084b2014-03-20 10:28:31 -07004315 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004316}
4317
Jamie Gennis6547ff42013-07-16 20:12:42 -07004318// This should only be called from the main thread. Otherwise it would need
4319// the lock and should use mCurrentState rather than mDrawingState.
4320void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004321 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004322 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004323 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004324
4325 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4326}
4327
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004328void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004329{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004330 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004331
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004332 if (isLayerTripleBufferingDisabled())
4333 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004334
4335 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004336 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004337 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004338 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004339 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4340 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004341 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004342}
4343
Dan Stozab90cf072015-03-05 11:05:59 -08004344void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4345{
4346 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004347 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4348 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004349 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004350 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004351 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4352 b + 1, bucketTimeSec, percent);
4353 }
David Sodman4a36e932017-11-07 14:29:47 -08004354 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004355 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004356 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004357 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004358 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004359}
4360
Dan Stozae77c7662016-05-13 11:37:28 -07004361void SurfaceFlinger::recordBufferingStats(const char* layerName,
4362 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004363 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4364 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004365 for (const auto& segment : history) {
4366 if (!segment.usedThirdBuffer) {
4367 stats.twoBufferTime += segment.totalTime;
4368 }
4369 if (segment.occupancyAverage < 1.0f) {
4370 stats.doubleBufferedTime += segment.totalTime;
4371 } else if (segment.occupancyAverage < 2.0f) {
4372 stats.tripleBufferedTime += segment.totalTime;
4373 }
4374 ++stats.numSegments;
4375 stats.totalTime += segment.totalTime;
4376 }
4377}
4378
Brian Andersond6927fb2016-07-23 23:37:30 -07004379void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4380 result.appendFormat("Layer frame timestamps:\n");
4381
4382 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4383 const size_t count = currentLayers.size();
4384 for (size_t i=0 ; i<count ; i++) {
4385 currentLayers[i]->dumpFrameEvents(result);
4386 }
4387}
4388
Dan Stozae77c7662016-05-13 11:37:28 -07004389void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4390 result.append("Buffering stats:\n");
4391 result.append(" [Layer name] <Active time> <Two buffer> "
4392 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004393 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004394 typedef std::tuple<std::string, float, float, float> BufferTuple;
4395 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004396 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004397 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004398 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004399 if (stats.numSegments == 0) {
4400 continue;
4401 }
4402 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4403 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4404 stats.totalTime;
4405 float doubleBufferRatio = static_cast<float>(
4406 stats.doubleBufferedTime) / stats.totalTime;
4407 float tripleBufferRatio = static_cast<float>(
4408 stats.tripleBufferedTime) / stats.totalTime;
4409 sorted.insert({activeTime, {name, twoBufferRatio,
4410 doubleBufferRatio, tripleBufferRatio}});
4411 }
4412 for (const auto& sortedPair : sorted) {
4413 float activeTime = sortedPair.first;
4414 const BufferTuple& values = sortedPair.second;
4415 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4416 std::get<0>(values).c_str(), activeTime,
4417 std::get<1>(values), std::get<2>(values),
4418 std::get<3>(values));
4419 }
4420 result.append("\n");
4421}
4422
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004423void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004424 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004425 const int32_t displayId = display->getId();
4426 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4427 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 continue;
4429 }
4430
Dominik Laskowski7e045462018-05-30 13:02:02 -07004431 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004432 uint8_t port;
4433 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004434 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004435 result.append("no identification data\n");
4436 continue;
4437 }
4438
4439 if (!isEdid(data)) {
4440 result.append("unknown identification data: ");
4441 for (uint8_t byte : data) {
4442 result.appendFormat("%x ", byte);
4443 }
4444 result.append("\n");
4445 continue;
4446 }
4447
4448 const auto edid = parseEdid(data);
4449 if (!edid) {
4450 result.append("invalid EDID: ");
4451 for (uint8_t byte : data) {
4452 result.appendFormat("%x ", byte);
4453 }
4454 result.append("\n");
4455 continue;
4456 }
4457
4458 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4459 result.append(edid->displayName.data(), edid->displayName.length());
4460 result.append("\"\n");
4461 }
4462 result.append("\n");
4463}
4464
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004465void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
Peiyong Lin13effd12018-07-24 17:01:47 -07004466 result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
4467 result.appendFormat("Device uses color management: %d\n", useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004468 result.appendFormat("DisplayColorSetting: %s\n",
4469 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004470
4471 // TODO: print out if wide-color mode is active or not
4472
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004473 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004474 const int32_t displayId = display->getId();
4475 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004476 continue;
4477 }
4478
Dominik Laskowski7e045462018-05-30 13:02:02 -07004479 result.appendFormat("Display %d color modes:\n", displayId);
4480 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004481 for (auto&& mode : modes) {
4482 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4483 }
4484
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004486 result.appendFormat(" Current color mode: %s (%d)\n",
4487 decodeColorMode(currentMode).c_str(), currentMode);
4488 }
4489 result.append("\n");
4490}
4491
David Sodman7e4ae112018-02-09 15:02:28 -08004492void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
4493 std::string stringResult;
4494
4495 for (const auto& [token, display] : mDisplays) {
4496 const auto displayId = display->getId();
4497 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
4498 continue;
4499 }
4500
4501 const auto& compositionInfoIt = getBE().mEndOfFrameCompositionInfo.find(displayId);
4502 if (compositionInfoIt == getBE().mEndOfFrameCompositionInfo.end()) {
4503 break;
4504 }
4505 const auto& compositionInfoList = compositionInfoIt->second;
4506 stringResult += base::StringPrintf("Display: %d\n", displayId);
4507 stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
4508 for (const auto& compositionInfo : compositionInfoList) {
4509 compositionInfo.dump(stringResult, nullptr);
4510 stringResult += base::StringPrintf("\n");
4511 }
4512 }
4513
4514 result.append(stringResult.c_str());
4515}
4516
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004517LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004518 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004519 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4520 const State& state = useDrawing ? mDrawingState : mCurrentState;
4521 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004522 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004523 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004524 });
4525
4526 return layersProto;
4527}
4528
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004529LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004530 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004531
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004532 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004533 resolution->set_w(display.getWidth());
4534 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004535
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004536 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4537 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4538 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004539
Dominik Laskowski7e045462018-05-30 13:02:02 -07004540 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004541 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004542 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004543 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004544 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004545 }
4546 });
4547
4548 return layersProto;
4549}
4550
Mathias Agopian74d211a2013-04-22 16:55:35 +02004551void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4552 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004553{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004554 bool colorize = false;
4555 if (index < args.size()
4556 && (args[index] == String16("--color"))) {
4557 colorize = true;
4558 index++;
4559 }
4560
4561 Colorizer colorizer(colorize);
4562
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004563 // figure out if we're stuck somewhere
4564 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004565 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004566 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4567
4568 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004569 * Dump library configuration.
4570 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571
4572 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004573 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004574 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004575 appendSfConfigString(result);
4576 appendUiConfigString(result);
4577 appendGuiConfigString(result);
4578 result.append("\n");
4579
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004580 result.append("\nDisplay identification data:\n");
4581 dumpDisplayIdentificationData(result);
4582
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004583 result.append("\nWide-Color information:\n");
4584 dumpWideColorInfo(result);
4585
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004586 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004587 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004588 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004589 result.append(SyncFeatures::getInstance().toString());
4590 result.append("\n");
4591
Andy McFadden41d67d72014-04-25 16:58:34 -07004592 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004593 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004594 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004595
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004596 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4597 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004598 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4599 getHwComposer().isConnected(displayId)) {
4600 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004601 result.appendFormat("Display %d: "
4602 "app phase %" PRId64 " ns, "
4603 "sf phase %" PRId64 " ns, "
4604 "early app phase %" PRId64 " ns, "
4605 "early sf phase %" PRId64 " ns, "
4606 "early app gl phase %" PRId64 " ns, "
4607 "early sf gl phase %" PRId64 " ns, "
4608 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4609 displayId,
4610 vsyncPhaseOffsetNs,
4611 sfVsyncPhaseOffsetNs,
4612 appEarlyOffset,
4613 sfEarlyOffset,
4614 appEarlyGlOffset,
Midas Chienbc5f22f2018-08-16 15:51:19 +08004615 sfEarlyGlOffset,
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004616 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004617 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004618 result.append("\n");
4619
Dan Stozab90cf072015-03-05 11:05:59 -08004620 // Dump static screen stats
4621 result.append("\n");
4622 dumpStaticScreenStats(result);
4623 result.append("\n");
4624
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004625 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4626
Dan Stozae77c7662016-05-13 11:37:28 -07004627 dumpBufferingStats(result);
4628
Andy McFadden4803b742012-09-24 19:07:20 -07004629 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004630 * Dump the visible layer list
4631 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004632 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004633 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004634 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4635 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004636 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004637
Chia-I Wu2f884132018-09-13 15:17:58 -07004638 {
4639 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4640 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4641 result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
4642 result.append("\n");
4643 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004644
David Sodman7e4ae112018-02-09 15:02:28 -08004645 result.append("\nFrame-Composition information:\n");
4646 dumpFrameCompositionInfo(result);
4647 result.append("\n");
4648
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004649 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004650 * Dump Display state
4651 */
4652
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004653 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004654 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004655 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004656 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004657 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004658 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004659 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004660
4661 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004662 * Dump SurfaceFlinger global state
4663 */
4664
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004665 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004666 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004667 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004668
Mathias Agopian888c8222012-08-04 21:10:38 -07004669 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004670 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004671
David Sodmanbc815282017-11-05 18:57:52 -08004672 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004673
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004674 if (display) {
4675 display->undefinedRegion.dump(result, "undefinedRegion");
4676 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4677 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004678 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08004679 result.appendFormat(" transaction-flags : %08x\n"
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004680 " gpu_to_cpu_unsupported : %d\n",
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004681 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004682
4683 if (display) {
4684 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4685 result.appendFormat(" refresh-rate : %f fps\n"
4686 " x-dpi : %f\n"
4687 " y-dpi : %f\n",
4688 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4689 activeConfig->getDpiY());
4690 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004691
Mathias Agopian74d211a2013-04-22 16:55:35 +02004692 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694
Ana Krulec98b5b242018-08-10 15:03:23 -07004695 result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004696 /*
4697 * VSYNC state
4698 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004699 if (mUseScheduler) {
4700 mScheduler->dump(mAppConnectionHandle, result);
4701 } else {
4702 mEventThread->dump(result);
4703 }
Dan Stozae22aec72016-08-01 13:20:59 -07004704 result.append("\n");
4705
4706 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004707 * Tracing state
4708 */
4709 mTracing.dump(result);
4710 result.append("\n");
4711
4712 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004713 * HWC layer minidump
4714 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004715 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004716 const int32_t displayId = display->getId();
4717 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004718 continue;
4719 }
4720
Dominik Laskowski7e045462018-05-30 13:02:02 -07004721 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004722 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004723 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004724 result.append("\n");
4725 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004726
4727 /*
4728 * Dump HWComposer state
4729 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004730 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004731 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004732 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004733 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004734 result.appendFormat(" h/w composer %s\n",
4735 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004736 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737
4738 /*
4739 * Dump gralloc state
4740 */
4741 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4742 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004743
4744 /*
4745 * Dump VrFlinger state if in use.
4746 */
4747 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4748 result.append("VrFlinger state:\n");
4749 result.append(mVrFlinger->Dump().c_str());
4750 result.append("\n");
4751 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752}
4753
Dominik Laskowski7e045462018-05-30 13:02:02 -07004754const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004755 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004756 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004757 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004758 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004759 }
4760 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004761
4762 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4763 static const Vector<sp<Layer>> empty;
4764 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004765}
4766
Keun young Park63f165f2012-08-31 10:53:36 -07004767bool SurfaceFlinger::startDdmConnection()
4768{
4769 void* libddmconnection_dso =
4770 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4771 if (!libddmconnection_dso) {
4772 return false;
4773 }
4774 void (*DdmConnection_start)(const char* name);
4775 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004776 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004777 if (!DdmConnection_start) {
4778 dlclose(libddmconnection_dso);
4779 return false;
4780 }
4781 (*DdmConnection_start)(getServiceName());
4782 return true;
4783}
4784
Chia-I Wu28f320b2018-05-03 11:02:56 -07004785void SurfaceFlinger::updateColorMatrixLocked() {
4786 mat4 colorMatrix;
4787 if (mGlobalSaturationFactor != 1.0f) {
4788 // Rec.709 luma coefficients
4789 float3 luminance{0.213f, 0.715f, 0.072f};
4790 luminance *= 1.0f - mGlobalSaturationFactor;
4791 mat4 saturationMatrix = mat4(
4792 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4793 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4794 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4795 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4796 );
4797 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4798 } else {
4799 colorMatrix = mClientColorMatrix * mDaltonizer();
4800 }
4801
4802 if (mCurrentState.colorMatrix != colorMatrix) {
4803 mCurrentState.colorMatrix = colorMatrix;
4804 mCurrentState.colorMatrixChanged = true;
4805 setTransactionFlags(eTransactionNeeded);
4806 }
4807}
4808
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004809status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810#pragma clang diagnostic push
4811#pragma clang diagnostic error "-Wswitch-enum"
4812 switch (static_cast<ISurfaceComposerTag>(code)) {
4813 // These methods should at minimum make sure that the client requested
4814 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004815 case BOOT_FINISHED:
4816 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 case CREATE_CONNECTION:
4818 case CREATE_DISPLAY:
4819 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004820 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821 case GET_ACTIVE_COLOR_MODE:
4822 case GET_ANIMATION_FRAME_STATS:
4823 case GET_HDR_CAPABILITIES:
4824 case SET_ACTIVE_CONFIG:
4825 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004826 case INJECT_VSYNC:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004828 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4829 IPCThreadState* ipc = IPCThreadState::self();
4830 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4831 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004832 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004833 }
Robert Carr1db73f62016-12-21 12:58:51 -08004834 return OK;
4835 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004836 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004837 IPCThreadState* ipc = IPCThreadState::self();
4838 const int pid = ipc->getCallingPid();
4839 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004840 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4841 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004842 return PERMISSION_DENIED;
4843 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004844 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004845 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004846 // Used by apps to hook Choreographer to SurfaceFlinger.
4847 case CREATE_DISPLAY_EVENT_CONNECTION:
4848 // The following calls are currently used by clients that do not
4849 // request necessary permissions. However, they do not expose any secret
4850 // information, so it is OK to pass them.
4851 case AUTHENTICATE_SURFACE:
4852 case GET_ACTIVE_CONFIG:
4853 case GET_BUILT_IN_DISPLAY:
4854 case GET_DISPLAY_COLOR_MODES:
4855 case GET_DISPLAY_CONFIGS:
4856 case GET_DISPLAY_STATS:
4857 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4858 // Calling setTransactionState is safe, because you need to have been
4859 // granted a reference to Client* and Handle* to do anything with it.
4860 case SET_TRANSACTION_STATE:
4861 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004862 case CREATE_SCOPED_CONNECTION:
4863 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 return OK;
4865 }
4866 case CAPTURE_LAYERS:
4867 case CAPTURE_SCREEN: {
4868 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004869 IPCThreadState* ipc = IPCThreadState::self();
4870 const int pid = ipc->getCallingPid();
4871 const int uid = ipc->getCallingUid();
4872 if ((uid != AID_GRAPHICS) &&
4873 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4874 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4875 return PERMISSION_DENIED;
4876 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004877 return OK;
4878 }
4879 // The following codes are deprecated and should never be allowed to access SF.
4880 case CONNECT_DISPLAY_UNUSED:
4881 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4882 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4883 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004884 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004885 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004886
4887 // These codes are used for the IBinder protocol to either interrogate the recipient
4888 // side of the transaction for its canonical interface descriptor or to dump its state.
4889 // We let them pass by default.
4890 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4891 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4892 code == IBinder::SYSPROPS_TRANSACTION) {
4893 return OK;
4894 }
4895 // Numbers from 1000 to 1029 are currently use for backdoors. The code
4896 // in onTransact verifies that the user is root, and has access to use SF.
4897 if (code >= 1000 && code <= 1029) {
4898 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4899 return OK;
4900 }
4901 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4902 return PERMISSION_DENIED;
4903#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004904}
4905
Ana Krulec13be8ad2018-08-21 02:43:56 +00004906status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4907 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004908 status_t credentialCheck = CheckTransactCodeCredentials(code);
4909 if (credentialCheck != OK) {
4910 return credentialCheck;
4911 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004912
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4914 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004915 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004916 IPCThreadState* ipc = IPCThreadState::self();
4917 const int uid = ipc->getCallingUid();
4918 if (CC_UNLIKELY(uid != AID_SYSTEM
4919 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004920 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004921 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004922 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 return PERMISSION_DENIED;
4924 }
4925 int n;
4926 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004927 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004928 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004929 return NO_ERROR;
4930 case 1002: // SHOW_UPDATES
4931 n = data.readInt32();
4932 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004933 invalidateHwcGeometry();
4934 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004935 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004936 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004937 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004938 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004939 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004940 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004941 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004942 setTransactionFlags(
4943 eTransactionNeeded|
4944 eDisplayTransactionNeeded|
4945 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004946 return NO_ERROR;
4947 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004948 case 1006:{ // send empty update
4949 signalRefresh();
4950 return NO_ERROR;
4951 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004952 case 1008: // toggle use of hw composer
4953 n = data.readInt32();
4954 mDebugDisableHWC = n ? 1 : 0;
4955 invalidateHwcGeometry();
4956 repaintEverything();
4957 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004958 case 1009: // toggle use of transform hint
4959 n = data.readInt32();
4960 mDebugDisableTransformHint = n ? 1 : 0;
4961 invalidateHwcGeometry();
4962 repaintEverything();
4963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004965 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004966 reply->writeInt32(0);
4967 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004968 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004969 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 return NO_ERROR;
4971 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004972 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004973 if (!display) {
4974 return NAME_NOT_FOUND;
4975 }
4976
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004977 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004978 return NO_ERROR;
4979 }
4980 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004981 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004982 // daltonize
4983 n = data.readInt32();
4984 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004985 case 1:
4986 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4987 break;
4988 case 2:
4989 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4990 break;
4991 case 3:
4992 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4993 break;
4994 default:
4995 mDaltonizer.setType(ColorBlindnessType::None);
4996 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004997 }
4998 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004999 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005000 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005001 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005002 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005003
5004 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005005 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005006 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005007 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005008 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005009 // apply a color matrix
5010 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005011 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005012 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005013 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005014 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005015 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005016 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005017 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005018 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005019 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005020 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005021
5022 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5023 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005024 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005025 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5026 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5027 }
5028
Chia-I Wu28f320b2018-05-03 11:02:56 -07005029 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005030 return NO_ERROR;
5031 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005032 // This is an experimental interface
5033 // Needs to be shifted to proper binder interface when we productize
5034 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005035 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07005036 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005037 return NO_ERROR;
5038 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005039 case 1017: {
5040 n = data.readInt32();
5041 mForceFullDamage = static_cast<bool>(n);
5042 return NO_ERROR;
5043 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005044 case 1018: { // Modify Choreographer's phase offset
5045 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005046 if (mUseScheduler) {
5047 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5048 } else {
5049 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5050 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005051 return NO_ERROR;
5052 }
5053 case 1019: { // Modify SurfaceFlinger's phase offset
5054 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005055 if (mUseScheduler) {
5056 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5057 } else {
5058 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5059 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005060 return NO_ERROR;
5061 }
Irvel468051e2016-06-13 16:44:44 -07005062 case 1020: { // Layer updates interceptor
5063 n = data.readInt32();
5064 if (n) {
5065 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005066 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005067 }
5068 else{
5069 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005070 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005071 }
5072 return NO_ERROR;
5073 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005074 case 1021: { // Disable HWC virtual displays
5075 n = data.readInt32();
5076 mUseHwcVirtualDisplays = !n;
5077 return NO_ERROR;
5078 }
Romain Guy0147a172017-06-01 13:53:56 -07005079 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005080 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005081 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005082
Chia-I Wu28f320b2018-05-03 11:02:56 -07005083 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005084 return NO_ERROR;
5085 }
Romain Guy54f154a2017-10-24 21:40:32 +01005086 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005087 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005088 invalidateHwcGeometry();
5089 repaintEverything();
5090 return NO_ERROR;
5091 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005092 // TODO(b/111505327): Find out whether the usage of 1024 can switch to 1030,
5093 // deprecate 1024 if they can.
5094 case 1024: { // Does device have wide color gamut display?
Romain Guy54f154a2017-10-24 21:40:32 +01005095 reply->writeBool(hasWideColorDisplay);
5096 return NO_ERROR;
5097 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005098 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005099 n = data.readInt32();
5100 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005101 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005102 mTracing.enable();
5103 doTracing("tracing.enable");
5104 reply->writeInt32(NO_ERROR);
5105 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005106 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005107 status_t err = mTracing.disable();
5108 reply->writeInt32(err);
5109 }
5110 return NO_ERROR;
5111 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005112 case 1026: { // Get layer tracing status
5113 reply->writeBool(mTracing.isEnabled());
5114 return NO_ERROR;
5115 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005116 // Is a DisplayColorSetting supported?
5117 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005118 const auto display = getDefaultDisplayDevice();
5119 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005120 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005121 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005122
5123 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5124 switch (setting) {
5125 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005126 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005127 break;
5128 case DisplayColorSetting::UNMANAGED:
5129 reply->writeBool(true);
5130 break;
5131 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005132 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005133 break;
5134 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005135 reply->writeBool(
5136 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005137 break;
5138 }
5139 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005140 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005141 // Is VrFlinger active?
5142 case 1028: {
5143 Mutex::Autolock _l(mStateLock);
5144 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5145 return NO_ERROR;
5146 }
David Sodman6d46c1e2018-07-13 12:59:48 -07005147 case 1029: {
5148 // Code 1029 is an experimental feature that allows applications to
5149 // simulate a high frequency panel by setting a multiplier and divisor
5150 // on the VSYNC-sf clock. If either the multiplier or divisor are
David Sodman44b5de02018-08-21 16:28:53 -07005151 // 0, then the code simply return the current multiplier and divisor.
5152 HWC2::Device::FrequencyScaler frequencyScaler;
5153 frequencyScaler.multiplier = data.readInt32();
5154 frequencyScaler.divisor = data.readInt32();
David Sodman6d46c1e2018-07-13 12:59:48 -07005155
David Sodman44b5de02018-08-21 16:28:53 -07005156 if ((frequencyScaler.multiplier == 0) || (frequencyScaler.divisor == 0)) {
5157 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5158 reply->writeInt32(frequencyScaler.multiplier);
5159 reply->writeInt32(frequencyScaler.divisor);
5160 return NO_ERROR;
David Sodman6d46c1e2018-07-13 12:59:48 -07005161 }
5162
David Sodman44b5de02018-08-21 16:28:53 -07005163 if ((frequencyScaler.multiplier == 1) && (frequencyScaler.divisor == 1)) {
David Sodman6d46c1e2018-07-13 12:59:48 -07005164 enableHardwareVsync();
5165 } else {
5166 disableHardwareVsync(true);
5167 }
David Sodman44b5de02018-08-21 16:28:53 -07005168 mPrimaryDispSync->scalePeriod(frequencyScaler);
5169 getBE().mHwc->setDisplayFrequencyScaleParameters(frequencyScaler);
David Sodman6d46c1e2018-07-13 12:59:48 -07005170
David Sodman44b5de02018-08-21 16:28:53 -07005171 ATRACE_INT("PeriodMultiplier", frequencyScaler.multiplier);
5172 ATRACE_INT("PeriodDivisor", frequencyScaler.divisor);
5173
5174 const hwc2_display_t hwcDisplayId = getBE().mHwc->getActiveConfig(
5175 DisplayDevice::DISPLAY_PRIMARY)->getDisplayId();
5176
5177 onHotplugReceived(getBE().mComposerSequenceId,
5178 hwcDisplayId, HWC2::Connection::Disconnected);
5179 onHotplugReceived(getBE().mComposerSequenceId,
5180 hwcDisplayId, HWC2::Connection::Connected);
5181 frequencyScaler = getBE().mHwc->getDisplayFrequencyScaleParameters();
5182 reply->writeInt32(frequencyScaler.multiplier);
5183 reply->writeInt32(frequencyScaler.divisor);
5184
David Sodman6d46c1e2018-07-13 12:59:48 -07005185 return NO_ERROR;
5186 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005187 // Is device color managed?
5188 case 1030: {
5189 reply->writeBool(useColorManagement);
5190 return NO_ERROR;
5191 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005192 }
5193 }
5194 return err;
5195}
5196
Steven Thomas6d8110b2017-08-31 18:24:21 -07005197void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005198 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005199 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005200}
5201
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005202// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5203class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005204public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005205 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5206 ~WindowDisconnector() {
5207 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005208 }
5209
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005210private:
5211 ANativeWindow* mWindow;
5212 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005213};
5214
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005215status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
5216 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005217 uint32_t reqWidth, uint32_t reqHeight,
5218 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005219 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005220 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005222 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005223
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005224 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5225
Chia-I Wu20261cb2018-08-23 12:55:44 -07005226 sp<DisplayDevice> display;
5227 {
5228 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005229
Chia-I Wu20261cb2018-08-23 12:55:44 -07005230 display = getDisplayDeviceLocked(displayToken);
5231 if (!display) return BAD_VALUE;
5232
Chia-I Wu8730ba82018-08-29 09:25:59 -07005233 // ignore sourceCrop (i.e., use the projected logical display
5234 // viewport) until the framework is fixed
5235 sourceCrop.clear();
Chia-I Wucb023152018-08-28 12:57:23 -07005236
5237 // set the requested width/height to the logical display viewport size
5238 // by default
5239 if (reqWidth == 0 || reqHeight == 0) {
5240 reqWidth = uint32_t(display->getViewport().width());
5241 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005242 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005243 }
5244
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005245 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005246
5247 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005248 display, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005249 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005250}
5251
5252status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08005253 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005254 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005255 ATRACE_CALL();
5256
5257 class LayerRenderArea : public RenderArea {
5258 public:
Robert Carr578038f2018-03-09 12:25:24 -08005259 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
5260 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
Chia-I Wu9d1abea2018-08-23 13:44:43 -07005261 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08005262 mLayer(layer),
5263 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005264 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005265 mFlinger(flinger),
5266 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005267 const ui::Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07005268 Rect getBounds() const override {
5269 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07005270 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07005271 }
Marissa Wall61c58622018-07-18 10:12:20 -07005272 int getHeight() const override {
5273 return mLayer->getActiveHeight(mLayer->getDrawingState());
5274 }
5275 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07005276 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005277 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005278 Rect getSourceCrop() const override {
5279 if (mCrop.isEmpty()) {
5280 return getBounds();
5281 } else {
5282 return mCrop;
5283 }
5284 }
Robert Carr578038f2018-03-09 12:25:24 -08005285 class ReparentForDrawing {
5286 public:
5287 const sp<Layer>& oldParent;
5288 const sp<Layer>& newParent;
5289
5290 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5291 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005292 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005293 }
Robert Carr15eae092018-03-23 13:43:53 -07005294 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005295 };
5296
5297 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005298 const Rect sourceCrop = getSourceCrop();
5299 // no need to check rotation because there is none
5300 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5301 sourceCrop.height() != getReqHeight();
5302
Robert Carr578038f2018-03-09 12:25:24 -08005303 if (!mChildrenOnly) {
5304 mTransform = mLayer->getTransform().inverse();
5305 drawLayers();
5306 } else {
5307 Rect bounds = getBounds();
5308 screenshotParentLayer =
5309 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5310 bounds.getWidth(), bounds.getHeight(), 0);
5311
5312 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5313 drawLayers();
5314 }
5315 }
chaviwa76b2712017-09-20 12:02:26 -07005316
chaviwa76b2712017-09-20 12:02:26 -07005317 private:
chaviw7206d492017-11-10 16:16:12 -08005318 const sp<Layer> mLayer;
5319 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005320
5321 // In the "childrenOnly" case we reparent the children to a screenshot
5322 // layer which has no properties set and which does not draw.
5323 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005324 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005325 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005326
5327 SurfaceFlinger* mFlinger;
5328 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005329 };
5330
5331 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5332 auto parent = layerHandle->owner.promote();
5333
chaviw7206d492017-11-10 16:16:12 -08005334 if (parent == nullptr || parent->isPendingRemoval()) {
5335 ALOGE("captureLayers called with a removed parent");
5336 return NAME_NOT_FOUND;
5337 }
5338
Robert Carr578038f2018-03-09 12:25:24 -08005339 const int uid = IPCThreadState::self()->getCallingUid();
5340 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5341 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5342 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5343 return PERMISSION_DENIED;
5344 }
5345
chaviw7206d492017-11-10 16:16:12 -08005346 Rect crop(sourceCrop);
5347 if (sourceCrop.width() <= 0) {
5348 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005349 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005350 }
5351
5352 if (sourceCrop.height() <= 0) {
5353 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005354 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005355 }
5356
5357 int32_t reqWidth = crop.width() * frameScale;
5358 int32_t reqHeight = crop.height() * frameScale;
5359
Chia-I Wu20261cb2018-08-23 12:55:44 -07005360 // really small crop or frameScale
5361 if (reqWidth <= 0) {
5362 reqWidth = 1;
5363 }
5364 if (reqHeight <= 0) {
5365 reqHeight = 1;
5366 }
5367
Robert Carr578038f2018-03-09 12:25:24 -08005368 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005369
Robert Carr578038f2018-03-09 12:25:24 -08005370 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005371 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5372 if (!layer->isVisible()) {
5373 return;
Robert Carr578038f2018-03-09 12:25:24 -08005374 } else if (childrenOnly && layer == parent.get()) {
5375 return;
chaviwa76b2712017-09-20 12:02:26 -07005376 }
5377 visitor(layer);
5378 });
5379 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005380 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005381}
5382
5383status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5384 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005385 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005386 bool useIdentityTransform) {
5387 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005388
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005389 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5390 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5391 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5392 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005393
5394 // This mutex protects syncFd and captureResult for communication of the return values from the
5395 // main thread back to this Binder thread
5396 std::mutex captureMutex;
5397 std::condition_variable captureCondition;
5398 std::unique_lock<std::mutex> captureLock(captureMutex);
5399 int syncFd = -1;
5400 std::optional<status_t> captureResult;
5401
Robert Carr03480e22018-01-04 16:02:06 -08005402 const int uid = IPCThreadState::self()->getCallingUid();
5403 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5404
Dominik Laskowski8c001672018-05-30 16:52:06 -07005405 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005406 // If there is a refresh pending, bug out early and tell the binder thread to try again
5407 // after the refresh.
5408 if (mRefreshPending) {
5409 ATRACE_NAME("Skipping screenshot for now");
5410 std::unique_lock<std::mutex> captureLock(captureMutex);
5411 captureResult = std::make_optional<status_t>(EAGAIN);
5412 captureCondition.notify_one();
5413 return;
5414 }
5415
5416 status_t result = NO_ERROR;
5417 int fd = -1;
5418 {
5419 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005420 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005421 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5422 useIdentityTransform, forSystem, &fd);
5423 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 }
5425
5426 {
5427 std::unique_lock<std::mutex> captureLock(captureMutex);
5428 syncFd = fd;
5429 captureResult = std::make_optional<status_t>(result);
5430 captureCondition.notify_one();
5431 }
5432 });
5433
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005434 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005435 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005436 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005437 while (*captureResult == EAGAIN) {
5438 captureResult.reset();
5439 result = postMessageAsync(message);
5440 if (result != NO_ERROR) {
5441 return result;
5442 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005443 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005444 }
5445 result = *captureResult;
5446 }
5447
5448 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005449 sync_wait(syncFd, -1);
5450 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005451 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005452
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005453 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005454}
5455
chaviwa76b2712017-09-20 12:02:26 -07005456void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005457 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005458 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005459 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005460
Lloyd Pique144e1162017-12-20 16:44:52 -08005461 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005462
chaviwa76b2712017-09-20 12:02:26 -07005463 const auto reqWidth = renderArea.getReqWidth();
5464 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005465 const auto sourceCrop = renderArea.getSourceCrop();
5466 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005467
Chia-I Wu36574d92018-05-16 10:54:36 -07005468 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5469 engine.setOutputDataSpace(Dataspace::SRGB);
5470 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005471
Mathias Agopian180f10d2013-04-10 22:55:41 -07005472 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005473 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005474
5475 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005476 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005477 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005478
chaviw50da5042018-04-09 13:49:37 -07005479 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005480 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005481 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005482
chaviwa76b2712017-09-20 12:02:26 -07005483 traverseLayers([&](Layer* layer) {
David Sodmanfb95bcc2017-12-22 15:45:30 -08005484 layer->draw(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005485 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005486}
5487
chaviwa76b2712017-09-20 12:02:26 -07005488status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5489 TraverseLayersFunction traverseLayers,
5490 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005491 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005492 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005493 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005494 ATRACE_CALL();
5495
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005496 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005497
5498 traverseLayers([&](Layer* layer) {
5499 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5500 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005501
Robert Carr03480e22018-01-04 16:02:06 -08005502 // We allow the system server to take screenshots of secure layers for
5503 // use in situations like the Screen-rotation animation and place
5504 // the impetus on WindowManager to not persist them.
5505 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005506 ALOGW("FB is protected: PERMISSION_DENIED");
5507 return PERMISSION_DENIED;
5508 }
5509
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005510 // this binds the given EGLImage as a framebuffer for the
5511 // duration of this scope.
Peiyong Lin833074a2018-08-28 11:53:54 -07005512 renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005513 if (bufferBond.getStatus() != NO_ERROR) {
5514 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005515 return INVALID_OPERATION;
5516 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005517
Dan Stozaabcda352017-06-01 14:37:39 -07005518 // this will in fact render into our dequeued buffer
5519 // via an FBO, which means we didn't have to create
5520 // an EGLSurface and therefore we're not
5521 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005522 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005523
Alec Mouri492bc572018-09-11 21:40:04 +00005524 base::unique_fd syncFd = getRenderEngine().flush();
5525 if (syncFd < 0) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005526 getRenderEngine().finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005527 }
Alec Mouri492bc572018-09-11 21:40:04 +00005528 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005529
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005530 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005531}
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,
chaviwa76b2712017-09-20 12:02:26 -07005544 const LayerVector::Visitor& visitor) {
5545 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005546 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005547 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005548 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005549 continue;
5550 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005551 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005552 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005553 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005554 return;
5555 }
chaviwa76b2712017-09-20 12:02:26 -07005556 if (!layer->isVisible()) {
5557 return;
5558 }
5559 visitor(layer);
5560 });
5561 }
5562}
5563
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005564}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005565
Lloyd Pique074e8122018-07-26 12:57:23 -07005566
Mathias Agopian3f844832013-08-07 21:24:32 -07005567#if defined(__gl_h_)
5568#error "don't include gl/gl.h in this file"
5569#endif
5570
5571#if defined(__gl2_h_)
5572#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005573#endif