blob: 1b0064f8da26b14024d79e476782e48aa03893e9 [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>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#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"
Robert Carr578038f2018-03-09 12:25:24 -080078#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079
Steven Thomasb02664d2017-07-26 18:48:28 -070080#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070081#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070082#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070083#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070084#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070085#include "Effects/Daltonizer.h"
Mathias Agopian875d8e12013-06-07 15:35:48 -070086#include "RenderEngine/RenderEngine.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070087#include "Scheduler/DispSync.h"
88#include "Scheduler/EventControlThread.h"
89#include "Scheduler/EventThread.h"
90
Mathias Agopianff2ed702013-09-01 21:36:12 -070091#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070092
Jiyong Park4b20c2e2017-01-14 19:45:11 +090093#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080094#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
95#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090096#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090097
chaviw1d044282017-09-27 12:19:28 -070098#include <layerproto/LayerProtoParser.h>
99
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800100#define DISPLAY_COUNT 1
101
Mathias Agopianfee2b462013-07-03 12:34:01 -0700102/*
103 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
104 * black pixels.
105 */
106#define DEBUG_SCREENSHOTS false
107
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800108namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109
Jaesoo Lee43518572017-01-23 19:03:16 +0900110using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900111using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700112using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700113using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700114using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700115using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900116
Steven Thomasb02664d2017-07-26 18:48:28 -0700117namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700118
119#pragma clang diagnostic push
120#pragma clang diagnostic error "-Wswitch-enum"
121
122bool isWideColorMode(const ColorMode colorMode) {
123 switch (colorMode) {
124 case ColorMode::DISPLAY_P3:
125 case ColorMode::ADOBE_RGB:
126 case ColorMode::DCI_P3:
127 case ColorMode::BT2020:
128 case ColorMode::BT2100_PQ:
129 case ColorMode::BT2100_HLG:
130 return true;
131 case ColorMode::NATIVE:
132 case ColorMode::STANDARD_BT601_625:
133 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
134 case ColorMode::STANDARD_BT601_525:
135 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
136 case ColorMode::STANDARD_BT709:
137 case ColorMode::SRGB:
138 return false;
139 }
140 return false;
141}
142
143#pragma clang diagnostic pop
144
Steven Thomasb02664d2017-07-26 18:48:28 -0700145class ConditionalLock {
146public:
147 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
148 if (lock) {
149 mMutex.lock();
150 }
151 }
152 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
153private:
154 Mutex& mMutex;
155 bool mLocked;
156};
Peiyong Linfca547f2018-07-09 13:03:33 -0700157
Steven Thomasb02664d2017-07-26 18:48:28 -0700158} // namespace anonymous
159
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800160// ---------------------------------------------------------------------------
161
Mathias Agopian99b49842011-06-27 16:05:52 -0700162const String16 sHardwareTest("android.permission.HARDWARE_TEST");
163const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
164const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
165const String16 sDump("android.permission.DUMP");
166
167// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800168int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
169int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700170int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700171bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800172uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800173bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800174bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800175int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800176// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600177bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700178
Kalle Raitaa099a242017-01-11 11:17:29 -0800179
180std::string getHwcServiceName() {
181 char value[PROPERTY_VALUE_MAX] = {};
182 property_get("debug.sf.hwc_service_name", value, "default");
183 ALOGI("Using HWComposer service: '%s'", value);
184 return std::string(value);
185}
186
187bool useTrebleTestingOverride() {
188 char value[PROPERTY_VALUE_MAX] = {};
189 property_get("debug.sf.treble_testing_override", value, "false");
190 ALOGI("Treble testing override: '%s'", value);
191 return std::string(value) == "true";
192}
193
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800194std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
195 switch(displayColorSetting) {
196 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700197 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800198 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700199 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800200 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700201 return std::string("Enhanced");
202 default:
203 return std::string("Unknown ") +
204 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800205 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206}
207
Lloyd Pique99d3da52018-01-22 17:48:03 -0800208NativeWindowSurface::~NativeWindowSurface() = default;
209
210namespace impl {
211
212class NativeWindowSurface final : public android::NativeWindowSurface {
213public:
214 static std::unique_ptr<android::NativeWindowSurface> create(
215 const sp<IGraphicBufferProducer>& producer) {
216 return std::make_unique<NativeWindowSurface>(producer);
217 }
218
219 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
220 : surface(new Surface(producer, false)) {}
221
222 ~NativeWindowSurface() override = default;
223
224private:
225 sp<ANativeWindow> getNativeWindow() const override { return surface; }
226
227 void preallocateBuffers() override { surface->allocateBuffers(); }
228
229 sp<Surface> surface;
230};
231
232} // namespace impl
233
David Sodmanbc815282017-11-05 18:57:52 -0800234SurfaceFlingerBE::SurfaceFlingerBE()
235 : mHwcServiceName(getHwcServiceName()),
236 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800237 mFrameBuckets(),
238 mTotalTime(0),
239 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800240 mComposerSequenceId(0) {
241}
242
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800243SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800244 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800245 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700246 mTransactionPending(false),
247 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700248 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700249 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700250 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800251 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700252 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800254 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800255 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800256 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700258 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700259 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700260 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700261 mDebugInSwapBuffers(0),
262 mLastSwapBufferTime(0),
263 mDebugInTransaction(0),
264 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700265 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800271 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800272 mCreateBufferQueue(&BufferQueue::createBufferQueue),
273 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
275SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
305
Iris Chang7501ed62018-04-30 14:45:42 +0800306 V1_1::DisplayOrientation primaryDisplayOrientation =
307 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
308 V1_1::DisplayOrientation::ORIENTATION_0);
309
310 switch (primaryDisplayOrientation) {
311 case V1_1::DisplayOrientation::ORIENTATION_90:
312 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
313 break;
314 case V1_1::DisplayOrientation::ORIENTATION_180:
315 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
316 break;
317 case V1_1::DisplayOrientation::ORIENTATION_270:
318 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
319 break;
320 default:
321 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
322 break;
323 }
324 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
325
Lloyd Pique41be5d22018-06-21 13:11:48 -0700326 // Note: We create a local temporary with the real DispSync implementation
327 // type temporarily so we can initialize it with the configured values,
328 // before storing it for more generic use using the interface type.
329 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
330 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
331 SurfaceFlinger::dispSyncPresentTimeOffset);
332 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700333
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334 // debugging stuff...
335 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700336
Mathias Agopianb4b17302013-03-20 18:36:41 -0700337 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700338 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800340 property_get("debug.sf.showupdates", value, "0");
341 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700342
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343 property_get("debug.sf.ddms", value, "0");
344 mDebugDDMS = atoi(value);
345 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700346 if (!startDdmConnection()) {
347 // start failed, and DDMS debugging not enabled
348 mDebugDDMS = 0;
349 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700350 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700351 ALOGI_IF(mDebugRegion, "showupdates enabled");
352 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700353
354 property_get("debug.sf.disable_backpressure", value, "0");
355 mPropagateBackpressure = !atoi(value);
356 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700357
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800358 property_get("debug.sf.enable_hwc_vds", value, "0");
359 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800360 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800361
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 property_get("ro.sf.disable_triple_buffer", value, "1");
363 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700365
Yiwei Zhang243b3782018-05-15 17:40:04 -0700366 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700367 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
368 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
369
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200370 property_get("debug.sf.early_phase_offset_ns", value, "-1");
371 const int earlySfOffsetNs = atoi(value);
372
373 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
374 const int earlyGlSfOffsetNs = atoi(value);
375
376 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
377 const int earlyAppOffsetNs = atoi(value);
378
379 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
380 const int earlyGlAppOffsetNs = atoi(value);
381
382 const VSyncModulator::Offsets earlyOffsets =
383 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
384 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
385 const VSyncModulator::Offsets earlyGlOffsets =
386 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
387 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
388 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
389 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700390
Romain Guy11d63f42017-07-20 12:47:14 -0700391 // We should be reading 'persist.sys.sf.color_saturation' here
392 // but since /data may be encrypted, we need to wait until after vold
393 // comes online to attempt to read the property. The property is
394 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800395
396 if (useTrebleTestingOverride()) {
397 // Without the override SurfaceFlinger cannot connect to HIDL
398 // services that are not listed in the manifests. Considered
399 // deriving the setting from the set service name, but it
400 // would be brittle if the name that's not 'default' is used
401 // for production purposes later on.
402 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
403 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404}
405
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406void SurfaceFlinger::onFirstRef()
407{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800408 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800409}
410
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800411SurfaceFlinger::~SurfaceFlinger()
412{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413}
414
Dan Stozac7014012014-02-14 15:03:43 -0800415void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416{
417 // the window manager died on us. prepare its eulogy.
418
Andy McFadden13a082e2012-08-24 10:16:42 -0700419 // restore initial conditions (default device unblank, etc)
420 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421
422 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700423 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
Robert Carr1db73f62016-12-21 12:58:51 -0800426static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700427 status_t err = client->initCheck();
428 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800429 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 }
Robert Carr1db73f62016-12-21 12:58:51 -0800431 return nullptr;
432}
433
434sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
435 return initClient(new Client(this));
436}
437
438sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
439 const sp<IGraphicBufferProducer>& gbp) {
440 if (authenticateSurfaceTexture(gbp) == false) {
441 return nullptr;
442 }
443 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
444 if (layer == nullptr) {
445 return nullptr;
446 }
447
448 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800449}
450
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700451sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
452 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453{
454 class DisplayToken : public BBinder {
455 sp<SurfaceFlinger> flinger;
456 virtual ~DisplayToken() {
457 // no more references, this display must be terminated
458 Mutex::Autolock _l(flinger->mStateLock);
459 flinger->mCurrentState.displays.removeItem(this);
460 flinger->setTransactionFlags(eDisplayTransactionNeeded);
461 }
462 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700463 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 : flinger(flinger) {
465 }
466 };
467
468 sp<BBinder> token = new DisplayToken(this);
469
470 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700471 DisplayDeviceState info;
472 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700473 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700474 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700475 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800476 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 return token;
478}
479
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700480void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700481 Mutex::Autolock _l(mStateLock);
482
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700483 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700485 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700486 return;
487 }
488
489 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700490 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700491 ALOGE("destroyDisplay called for non-virtual display");
492 return;
493 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700494 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700495 mCurrentState.displays.removeItemsAt(idx);
496 setTransactionFlags(eDisplayTransactionNeeded);
497}
498
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700500 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700501 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800502 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700504 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
516 // wait patiently for the window manager death
517 const String16 name("window");
518 sp<IBinder> window(defaultServiceManager()->getService(name));
519 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700520 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700521 }
522
Steven Thomas050b2c82017-03-06 11:45:16 -0800523 if (mVrFlinger) {
524 mVrFlinger->OnBootFinished();
525 }
526
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700528 // formerly we would just kill the process, but we now ask it to exit so it
529 // can choose where to stop the animation.
530 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700531
532 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
533 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
534 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700535
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800536 postMessageAsync(new LambdaMessage([this] {
537 readPersistentProperties();
538 mBootStage = BootStage::FINISHED;
539 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800540}
541
Dan Stoza436ccf32018-06-21 12:10:12 -0700542uint32_t SurfaceFlinger::getNewTexture() {
543 {
544 std::lock_guard lock(mTexturePoolMutex);
545 if (!mTexturePool.empty()) {
546 uint32_t name = mTexturePool.back();
547 mTexturePool.pop_back();
548 ATRACE_INT("TexturePoolSize", mTexturePool.size());
549 return name;
550 }
551
552 // The pool was too small, so increase it for the future
553 ++mTexturePoolSize;
554 }
555
556 // The pool was empty, so we need to get a new texture name directly using a
557 // blocking call to the main thread
558 uint32_t name = 0;
559 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
560 return name;
561}
562
Mathias Agopian3f844832013-08-07 21:24:32 -0700563void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700564 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700565}
566
Lloyd Piquee83f9312018-02-01 12:53:17 -0800567class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700569 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000570 const char* name) :
571 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700572 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000574 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
575 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700576 mDispSync(dispSync),
577 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700578 mVsyncMutex(),
579 mPhaseOffset(phaseOffset),
580 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700581
Lloyd Piquee83f9312018-02-01 12:53:17 -0800582 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700583
Lloyd Piquee83f9312018-02-01 12:53:17 -0800584 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700585 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700586 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000587 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588 static_cast<DispSync::Callback*>(this));
589 if (err != NO_ERROR) {
590 ALOGE("error registering vsync callback: %s (%d)",
591 strerror(-err), err);
592 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700593 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594 } else {
595 status_t err = mDispSync->removeEventListener(
596 static_cast<DispSync::Callback*>(this));
597 if (err != NO_ERROR) {
598 ALOGE("error unregistering vsync callback: %s (%d)",
599 strerror(-err), err);
600 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700601 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700603 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700604 }
605
Lloyd Piquee83f9312018-02-01 12:53:17 -0800606 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700607 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700608 mCallback = callback;
609 }
610
Lloyd Piquee83f9312018-02-01 12:53:17 -0800611 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700612 Mutex::Autolock lock(mVsyncMutex);
613
614 // Normalize phaseOffset to [0, period)
615 auto period = mDispSync->getPeriod();
616 phaseOffset %= period;
617 if (phaseOffset < 0) {
618 // If we're here, then phaseOffset is in (-period, 0). After this
619 // operation, it will be in (0, period)
620 phaseOffset += period;
621 }
622 mPhaseOffset = phaseOffset;
623
624 // If we're not enabled, we don't need to mess with the listeners
625 if (!mEnabled) {
626 return;
627 }
628
Dan Stoza84d619e2018-03-28 17:07:36 -0700629 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
630 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700631 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700632 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700633 strerror(-err), err);
634 }
635 }
636
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700637private:
638 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800639 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700640 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700641 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700642 callback = mCallback;
643
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700644 if (mTraceVsync) {
645 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700646 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700647 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700648 }
649
Peiyong Lin566a3b42018-01-09 18:22:43 -0800650 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700651 callback->onVSyncEvent(when);
652 }
653 }
654
Tim Murray4a4e4a22016-04-19 16:29:23 +0000655 const char* const mName;
656
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700657 int mValue;
658
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700659 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700660 const String8 mVsyncOnLabel;
661 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700662
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700663 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700664
665 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800666 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700667
668 Mutex mVsyncMutex; // Protects the following
669 nsecs_t mPhaseOffset;
670 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700671};
672
Lloyd Piquee83f9312018-02-01 12:53:17 -0800673class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700674public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800675 InjectVSyncSource() = default;
676 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700677
Lloyd Piquee83f9312018-02-01 12:53:17 -0800678 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700679 std::lock_guard<std::mutex> lock(mCallbackMutex);
680 mCallback = callback;
681 }
682
Lloyd Piquee83f9312018-02-01 12:53:17 -0800683 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700684 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700685 if (mCallback) {
686 mCallback->onVSyncEvent(when);
687 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700688 }
689
Lloyd Piquee83f9312018-02-01 12:53:17 -0800690 void setVSyncEnabled(bool) override {}
691 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700692
693private:
694 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800695 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700696};
697
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698// Do not call property_set on main thread which will be blocked by init
699// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700700void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700701 ALOGI( "SurfaceFlinger's main thread ready to run. "
702 "Initializing graphics H/W...");
703
Thierry Strudel2924d012017-08-14 15:19:37 -0700704 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900705
Steven Thomasb02664d2017-07-26 18:48:28 -0700706 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800707
Steven Thomasb02664d2017-07-26 18:48:28 -0700708 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800709 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700710 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
711 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800712 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700713 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800714 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800715 "appEventThread");
716 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700717 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800718 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800719
Lloyd Pique24b0a482018-03-09 18:52:26 -0800720 mSFEventThread =
721 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700722 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800723 [this](nsecs_t timestamp) {
724 mInterceptor->saveVSyncEvent(timestamp);
725 },
726 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800727 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200728 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800729
Steven Thomasb02664d2017-07-26 18:48:28 -0700730 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800731 getBE().mRenderEngine =
732 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
733 hasWideColorDisplay
734 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
735 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800736 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700737
738 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
739 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800740 getBE().mHwc.reset(
741 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700742 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800743 // Process any initial hotplug and resulting display changes.
744 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700745 const auto display = getDefaultDisplayDeviceLocked();
746 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
747 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
748 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800749
Lloyd Piquefcd86612017-12-14 17:15:36 -0800750 // make the default display GLContext current so that we can create textures
751 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700752 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800753
Steven Thomas050b2c82017-03-06 11:45:16 -0800754 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700755 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700756 // This callback is called from the vr flinger dispatch thread. We
757 // need to call signalTransaction(), which requires holding
758 // mStateLock when we're not on the main thread. Acquiring
759 // mStateLock from the vr flinger dispatch thread might trigger a
760 // deadlock in surface flinger (see b/66916578), so post a message
761 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700762 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700763 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
764 mVrFlingerRequestsDisplay = requestDisplay;
765 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700766 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800767 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700768 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
769 getHwComposer()
770 .getHwcDisplayId(display->getId())
771 .value_or(0),
772 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800773 if (!mVrFlinger) {
774 ALOGE("Failed to start vrflinger");
775 }
776 }
777
Lloyd Pique379adc12018-01-22 17:31:47 -0800778 mEventControlThread = std::make_unique<impl::EventControlThread>(
779 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700780
Mathias Agopian92a979a2012-08-02 18:32:23 -0700781 // initialize our drawing state
782 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700783
Andy McFadden13a082e2012-08-24 10:16:42 -0700784 // set initial conditions (e.g. unblank default device)
785 initializeDisplays();
786
David Sodmanbc815282017-11-05 18:57:52 -0800787 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700788
Wei Wangf9b05ee2017-07-19 20:59:39 -0700789 // Inform native graphics APIs whether the present timestamp is supported:
790 if (getHwComposer().hasCapability(
791 HWC2::Capability::PresentFenceIsNotReliable)) {
792 mStartPropertySetThread = new StartPropertySetThread(false);
793 } else {
794 mStartPropertySetThread = new StartPropertySetThread(true);
795 }
796
797 if (mStartPropertySetThread->Start() != NO_ERROR) {
798 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800799 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800800
Chia-I Wud49d6692018-06-27 07:17:41 +0800801 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
802 // is used to saturate legacy sRGB content. However, to make sure the same color under
803 // Display P3 will be saturated to the same color, we intentionally break the API spec
804 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
805 // such saturation matrix on Display P3 is understood fully, the API should always return
806 // identify matrix.
807 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
808 Dataspace::SRGB_LINEAR);
809
810 // we will apply this on Display P3.
811 if (mEnhancedSaturationMatrix != mat4()) {
812 ColorSpace srgb(ColorSpace::sRGB());
813 ColorSpace displayP3(ColorSpace::DisplayP3());
814 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
815 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
816 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
817 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800818
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700820}
821
Romain Guy11d63f42017-07-20 12:47:14 -0700822void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700823 Mutex::Autolock _l(mStateLock);
824
Romain Guy11d63f42017-07-20 12:47:14 -0700825 char value[PROPERTY_VALUE_MAX];
826
827 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800828 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700829 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800830 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100831
832 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700833 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700834}
835
Mathias Agopiana67e4182012-06-19 17:26:12 -0700836void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800837 // Start boot animation service by setting a property mailbox
838 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700839 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800840 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700841 if (mStartPropertySetThread->join() != NO_ERROR) {
842 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800843 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700844}
845
Mathias Agopian875d8e12013-06-07 15:35:48 -0700846size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800847 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700848}
849
Mathias Agopian875d8e12013-06-07 15:35:48 -0700850size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800851 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700852}
853
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800854// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800855
Jamie Gennis582270d2011-08-17 18:19:00 -0700856bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800857 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800858 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800859 return authenticateSurfaceTextureLocked(bufferProducer);
860}
861
862bool SurfaceFlinger::authenticateSurfaceTextureLocked(
863 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800864 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800865 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800866}
867
Brian Anderson6b376712017-04-04 10:51:39 -0700868status_t SurfaceFlinger::getSupportedFrameTimestamps(
869 std::vector<FrameEvent>* outSupported) const {
870 *outSupported = {
871 FrameEvent::REQUESTED_PRESENT,
872 FrameEvent::ACQUIRE,
873 FrameEvent::LATCH,
874 FrameEvent::FIRST_REFRESH_START,
875 FrameEvent::LAST_REFRESH_START,
876 FrameEvent::GPU_COMPOSITION_DONE,
877 FrameEvent::DEQUEUE_READY,
878 FrameEvent::RELEASE,
879 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700880 ConditionalLock _l(mStateLock,
881 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700882 if (!getHwComposer().hasCapability(
883 HWC2::Capability::PresentFenceIsNotReliable)) {
884 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
885 }
886 return NO_ERROR;
887}
888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
890 Vector<DisplayInfo>* configs) {
891 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 return BAD_VALUE;
893 }
894
Jesse Hall692c7232012-11-08 15:41:56 -0800895 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
897 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700898 type = i;
899 break;
900 }
901 }
902
903 if (type < 0) {
904 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700905 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700906
Mathias Agopian8b736f12012-08-13 17:54:26 -0700907 // TODO: Not sure if display density should handled by SF any longer
908 class Density {
909 static int getDensityFromProperty(char const* propName) {
910 char property[PROPERTY_VALUE_MAX];
911 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800912 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 density = atoi(property);
914 }
915 return density;
916 }
917 public:
918 static int getEmuDensity() {
919 return getDensityFromProperty("qemu.sf.lcd_density"); }
920 static int getBuildDensity() {
921 return getDensityFromProperty("ro.sf.lcd_density"); }
922 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700923
Dan Stoza7f7da322014-05-02 15:26:25 -0700924 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700925
Steven Thomas6d8110b2017-08-31 18:24:21 -0700926 ConditionalLock _l(mStateLock,
927 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800928 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700929 DisplayInfo info = DisplayInfo();
930
Dan Stoza9e56aa02015-11-02 13:00:03 -0800931 float xdpi = hwConfig->getDpiX();
932 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700933
934 if (type == DisplayDevice::DISPLAY_PRIMARY) {
935 // The density of the device is provided by a build property
936 float density = Density::getBuildDensity() / 160.0f;
937 if (density == 0) {
938 // the build doesn't provide a density -- this is wrong!
939 // use xdpi instead
940 ALOGE("ro.sf.lcd_density must be defined as a build property");
941 density = xdpi / 160.0f;
942 }
943 if (Density::getEmuDensity()) {
944 // if "qemu.sf.lcd_density" is specified, it overrides everything
945 xdpi = ydpi = density = Density::getEmuDensity();
946 density /= 160.0f;
947 }
948 info.density = density;
949
950 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 const auto display = getDefaultDisplayDeviceLocked();
952 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700953 } else {
954 // TODO: where should this value come from?
955 static const int TV_DENSITY = 213;
956 info.density = TV_DENSITY / 160.0f;
957 info.orientation = 0;
958 }
959
Dan Stoza9e56aa02015-11-02 13:00:03 -0800960 info.w = hwConfig->getWidth();
961 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700962 info.xdpi = xdpi;
963 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800964 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900965 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800966
Andy McFadden91b2ca82014-06-13 14:04:23 -0700967 // This is how far in advance a buffer must be queued for
968 // presentation at a given time. If you want a buffer to appear
969 // on the screen at time N, you must submit the buffer before
970 // (N - presentationDeadline).
971 //
972 // Normally it's one full refresh period (to give SF a chance to
973 // latch the buffer), but this can be reduced by configuring a
974 // DispSync offset. Any additional delays introduced by the hardware
975 // composer or panel must be accounted for here.
976 //
977 // We add an additional 1ms to allow for processing time and
978 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800979 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800980 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700981
982 // All non-virtual displays are currently considered secure.
983 info.secure = true;
984
Iris Chang7501ed62018-04-30 14:45:42 +0800985 if (type == DisplayDevice::DISPLAY_PRIMARY &&
986 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
987 std::swap(info.w, info.h);
988 }
989
Michael Wright28f24d02016-07-12 13:30:53 -0700990 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700991 }
992
Dan Stoza7f7da322014-05-02 15:26:25 -0700993 return NO_ERROR;
994}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700995
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700996status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
997 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700998 return BAD_VALUE;
999 }
1000
1001 // FIXME for now we always return stats for the primary display
1002 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -07001003 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1004 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001005 return NO_ERROR;
1006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1009 const auto display = getDisplayDevice(displayToken);
1010 if (!display) {
1011 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001012 return BAD_VALUE;
1013 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001016}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1019 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001020 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001025 ALOGW("Trying to set config for virtual display");
1026 return;
1027 }
1028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001029 display->setActiveConfig(mode);
1030 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001031}
1032
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001033status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001034 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 Vector<DisplayInfo> configs;
1036 getDisplayConfigs(displayToken, &configs);
1037 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1038 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1039 configs.size());
1040 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001041 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001042 const auto display = getDisplayDevice(displayToken);
1043 if (!display) {
1044 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1045 displayToken.get());
1046 } else if (display->isVirtual()) {
1047 ALOGW("Attempt to set active config %d for virtual display", mode);
1048 } else {
1049 setActiveConfigInternal(display, mode);
1050 }
1051 }));
1052
Mathias Agopian888c8222012-08-04 21:10:38 -07001053 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001054}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1056 Vector<ColorMode>* outColorModes) {
1057 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001058 return BAD_VALUE;
1059 }
1060
Michael Wright28f24d02016-07-12 13:30:53 -07001061 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1063 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001064 type = i;
1065 break;
1066 }
1067 }
1068
1069 if (type < 0) {
1070 return type;
1071 }
1072
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001074 {
1075 ConditionalLock _l(mStateLock,
1076 std::this_thread::get_id() != mMainThreadId);
1077 modes = getHwComposer().getColorModes(type);
1078 }
Michael Wright28f24d02016-07-12 13:30:53 -07001079 outColorModes->clear();
1080 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1081
1082 return NO_ERROR;
1083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1086 if (const auto display = getDisplayDevice(displayToken)) {
1087 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001088 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1093 Dataspace dataSpace, RenderIntent renderIntent) {
1094 ColorMode currentMode = display->getActiveColorMode();
1095 Dataspace currentDataSpace = display->getCompositionDataSpace();
1096 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001097
Peiyong Lin38e9a562018-04-10 16:24:20 -07001098 if (mode == currentMode && dataSpace == currentDataSpace &&
1099 renderIntent == currentRenderIntent) {
1100 return;
1101 }
1102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001104 ALOGW("Trying to set config for virtual display");
1105 return;
1106 }
1107
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 display->setActiveColorMode(mode);
1109 display->setCompositionDataSpace(dataSpace);
1110 display->setActiveRenderIntent(renderIntent);
1111 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001112
1113 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1115 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001119 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120 Vector<ColorMode> modes;
1121 getDisplayColorModes(displayToken, &modes);
1122 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1123 if (mode < ColorMode::NATIVE || !exists) {
1124 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1125 decodeColorMode(mode).c_str(), mode, displayToken.get());
1126 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001127 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const auto display = getDisplayDevice(displayToken);
1129 if (!display) {
1130 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1131 decodeColorMode(mode).c_str(), mode, displayToken.get());
1132 } else if (display->isVirtual()) {
1133 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1134 decodeColorMode(mode).c_str(), mode);
1135 } else {
1136 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1137 RenderIntent::COLORIMETRIC);
1138 }
1139 }));
1140
Michael Wright28f24d02016-07-12 13:30:53 -07001141 return NO_ERROR;
1142}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001143
Svetoslavd85084b2014-03-20 10:28:31 -07001144status_t SurfaceFlinger::clearAnimationFrameStats() {
1145 Mutex::Autolock _l(mStateLock);
1146 mAnimFrameTracker.clearStats();
1147 return NO_ERROR;
1148}
1149
1150status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1151 Mutex::Autolock _l(mStateLock);
1152 mAnimFrameTracker.getStats(outStats);
1153 return NO_ERROR;
1154}
1155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1157 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001158 Mutex::Autolock _l(mStateLock);
1159
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001160 const auto display = getDisplayDeviceLocked(displayToken);
1161 if (!display) {
1162 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001163 return BAD_VALUE;
1164 }
1165
Peiyong Linfb069302018-04-25 14:34:31 -07001166 // At this point the DisplayDeivce should already be set up,
1167 // meaning the luminance information is already queried from
1168 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001169 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001170 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1171 capabilities.getDesiredMaxLuminance(),
1172 capabilities.getDesiredMaxAverageLuminance(),
1173 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001174
1175 return NO_ERROR;
1176}
1177
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001179 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001180 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001181
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 if (mInjectVSyncs == enable) {
1183 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001184 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001185
1186 if (enable) {
1187 ALOGV("VSync Injections enabled");
1188 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001189 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001190 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001191 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001192 impl::EventThread::InterceptVSyncsCallback(),
1193 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001194 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001195 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001196 } else {
1197 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001198 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001199 }
1200
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001201 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001202 }));
1203
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001204 return NO_ERROR;
1205}
1206
1207status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001208 Mutex::Autolock _l(mStateLock);
1209
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001210 if (!mInjectVSyncs) {
1211 ALOGE("VSync Injections not enabled");
1212 return BAD_VALUE;
1213 }
1214 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1215 ALOGV("Injecting VSync inside SurfaceFlinger");
1216 mVSyncInjector->onInjectSyncEvent(when);
1217 }
1218 return NO_ERROR;
1219}
1220
Lloyd Pique755e3192018-01-31 16:46:15 -08001221status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1222 NO_THREAD_SAFETY_ANALYSIS {
Peiyong Line70e1292018-08-09 14:06:58 -07001223 IPCThreadState* ipc = IPCThreadState::self();
1224 const int pid = ipc->getCallingPid();
1225 const int uid = ipc->getCallingUid();
1226 if ((uid != AID_SHELL) &&
1227 !PermissionCache::checkPermission(sDump, pid, uid)) {
1228 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
1229 return PERMISSION_DENIED;
1230 }
1231
Kalle Raitaa099a242017-01-11 11:17:29 -08001232 // Try to acquire a lock for 1s, fail gracefully
1233 const status_t err = mStateLock.timedLock(s2ns(1));
1234 const bool locked = (err == NO_ERROR);
1235 if (!locked) {
1236 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1237 return TIMED_OUT;
1238 }
1239
1240 outLayers->clear();
1241 mCurrentState.traverseInZOrder([&](Layer* layer) {
1242 outLayers->push_back(layer->getLayerDebugInfo());
1243 });
1244
1245 mStateLock.unlock();
1246 return NO_ERROR;
1247}
1248
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001249// ----------------------------------------------------------------------------
1250
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001251sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1252 ISurfaceComposer::VsyncSource vsyncSource) {
1253 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1254 return mSFEventThread->createEventConnection();
1255 } else {
1256 return mEventThread->createEventConnection();
1257 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001258}
1259
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001260// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261
1262void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001263 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001264}
1265
1266void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001267 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001268}
1269
1270void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001271 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001272}
1273
1274void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001275 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001276 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001277}
1278
1279status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001280 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001281 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001282}
1283
1284status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001285 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001286 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001287 if (res == NO_ERROR) {
1288 msg->wait();
1289 }
1290 return res;
1291}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001292
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001293void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001294 do {
1295 waitForEvent();
1296 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001297}
1298
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001299void SurfaceFlinger::enableHardwareVsync() {
1300 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001301 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001302 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001303 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001304 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001305 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001306}
1307
Jesse Hall948fe0c2013-10-14 12:56:09 -07001308void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309 Mutex::Autolock _l(mHWVsyncLock);
1310
Jesse Hall948fe0c2013-10-14 12:56:09 -07001311 if (makeAvailable) {
1312 mHWVsyncAvailable = true;
1313 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001314 // Hardware vsync is not currently available, so abort the resync
1315 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001316 return;
1317 }
1318
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001319 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1320 if (!getHwComposer().isConnected(displayId)) {
1321 return;
1322 }
1323
1324 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001325 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326
Lloyd Pique41be5d22018-06-21 13:11:48 -07001327 mPrimaryDispSync->reset();
1328 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001329
1330 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001331 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001332 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001333 mPrimaryHWVsyncEnabled = true;
1334 }
1335}
1336
Jesse Hall948fe0c2013-10-14 12:56:09 -07001337void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001338 Mutex::Autolock _l(mHWVsyncLock);
1339 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001340 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001341 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001342 mPrimaryHWVsyncEnabled = false;
1343 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001344 if (makeUnavailable) {
1345 mHWVsyncAvailable = false;
1346 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001347}
1348
Tim Murray4a4e4a22016-04-19 16:29:23 +00001349void SurfaceFlinger::resyncWithRateLimit() {
1350 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001351
1352 // No explicit locking is needed here since EventThread holds a lock while calling this method
1353 static nsecs_t sLastResyncAttempted = 0;
1354 const nsecs_t now = systemTime();
1355 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001356 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001357 }
Dan Stoza57164302017-05-08 14:03:54 -07001358 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001359}
1360
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001361void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1362 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001363 ATRACE_NAME("SF onVsync");
1364
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001366 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001367 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001368 return;
1369 }
1370
1371 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001372 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 return;
1374 }
1375
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001376 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1377 // For now, we don't do anything with external display vsyncs.
1378 return;
1379 }
1380
Jamie Gennisd1700752013-10-14 12:22:52 -07001381 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001382
Jamie Gennisd1700752013-10-14 12:22:52 -07001383 { // Scope for the lock
1384 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001385 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001386 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001387 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001388 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001389
1390 if (needsHwVsync) {
1391 enableHardwareVsync();
1392 } else {
1393 disableHardwareVsync(false);
1394 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001395}
1396
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001398 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1399 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001400}
1401
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001402void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001403 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001404 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001405 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001406
Lloyd Piqueba04e622017-12-14 17:11:26 -08001407 // Ignore events that do not have the right sequenceId.
1408 if (sequenceId != getBE().mComposerSequenceId) {
1409 return;
1410 }
1411
Steven Thomasb02664d2017-07-26 18:48:28 -07001412 // Only lock if we're not on the main thread. This function is normally
1413 // called on a hwbinder thread, but for the primary display it's called on
1414 // the main thread with the state lock already held, so don't attempt to
1415 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001416 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001417
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001418 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001419
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001420 if (std::this_thread::get_id() == mMainThreadId) {
1421 // Process all pending hot plug events immediately if we are on the main thread.
1422 processDisplayHotplugEventsLocked();
1423 }
1424
Lloyd Piqueba04e622017-12-14 17:11:26 -08001425 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001426}
1427
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001428void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001429 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001430 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001431 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001432 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001433 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001434}
1435
Dan Stoza9e56aa02015-11-02 13:00:03 -08001436void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001437 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001439 getHwComposer().setVsyncEnabled(disp,
1440 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001441}
1442
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001443// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001444void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001445 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 // Clear the drawing state so that the logic inside of
1447 // handleTransactionLocked will fire. It will determine the delta between
1448 // mCurrentState and mDrawingState and re-apply all changes when we make the
1449 // transition.
1450 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001451 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001452 mDisplays.clear();
1453}
1454
Steven Thomas050b2c82017-03-06 11:45:16 -08001455void SurfaceFlinger::updateVrFlinger() {
1456 if (!mVrFlinger)
1457 return;
1458 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001459 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001460 return;
1461 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001462
David Sodman105b7dc2017-11-04 20:28:14 -07001463 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001464 ALOGE("Vr flinger is only supported for remote hardware composer"
1465 " service connections. Ignoring request to transition to vr"
1466 " flinger.");
1467 mVrFlingerRequestsDisplay = false;
1468 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001469 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001470
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472
Steven Thomas0123ac62018-07-12 11:32:34 -07001473 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001474 LOG_ALWAYS_FATAL_IF(!display);
1475 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001476 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1477 // called below. Clear the reference now so we don't accidentally use it
1478 // later.
1479 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001480
Steven Thomasb02664d2017-07-26 18:48:28 -07001481 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001483 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001484
Steven Thomasb02664d2017-07-26 18:48:28 -07001485 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001486 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001487 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1488 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001489 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001490
David Sodman105b7dc2017-11-04 20:28:14 -07001491 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1492 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001493
1494 if (vrFlingerRequestsDisplay) {
1495 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001496 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497
1498 mVisibleRegionsDirty = true;
1499 invalidateHwcGeometry();
1500
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001501 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001502 display = getDefaultDisplayDeviceLocked();
1503 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001504 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001505
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001507 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 const nsecs_t period = activeConfig->getVsyncPeriod();
1509 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001510
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001511 // The present fences returned from vr_hwc are not an accurate
1512 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001513 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1514 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001515
Steven Thomasb02664d2017-07-26 18:48:28 -07001516 // Use phase of 0 since phase is not known.
1517 // Use latency of 0, which will snap to the ideal latency.
1518 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001519
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001520 resyncToHardwareVsync(false);
1521
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001522 android_atomic_or(1, &mRepaintEverything);
1523 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001524}
1525
Mathias Agopian4fec8732012-06-29 14:12:52 -07001526void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001527 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001529 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001530 bool frameMissed = !mHadClientComposition &&
1531 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001532 (mPreviousPresentFence->getSignalTime() ==
1533 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001534 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001535 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001536 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001537 mTimeStats.incrementMissedFrames();
1538 if (mPropagateBackpressure) {
1539 signalLayerUpdate();
1540 break;
1541 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001542 }
Dan Stoza50182882016-07-08 12:02:20 -07001543
Steven Thomas050b2c82017-03-06 11:45:16 -08001544 // Now that we're going to make it to the handleMessageTransaction()
1545 // call below it's safe to call updateVrFlinger(), which will
1546 // potentially trigger a display handoff.
1547 updateVrFlinger();
1548
Dan Stoza6b9454d2014-11-07 16:00:59 -08001549 bool refreshNeeded = handleMessageTransaction();
1550 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001551 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001552 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001553 // Signal a refresh if a transaction modified the window state,
1554 // a new buffer was latched, or if HWC has requested a full
1555 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001556 signalRefresh();
1557 }
1558 break;
1559 }
1560 case MessageQueue::REFRESH: {
1561 handleMessageRefresh();
1562 break;
1563 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001564 }
1565}
1566
Dan Stoza6b9454d2014-11-07 16:00:59 -08001567bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001568 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001569 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001570 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001571 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001572 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001573 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001574}
1575
Dan Stoza6b9454d2014-11-07 16:00:59 -08001576bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001577 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001578 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579}
1580
1581void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001582 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001583
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001584 mRefreshPending = false;
1585
Lloyd Pique074e8122018-07-26 12:57:23 -07001586 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1587
1588 preComposition(refreshStartTime);
1589 rebuildLayerStacks();
1590 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001591 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001592 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001593 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001594 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001595 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001596
Dan Stozabfbffeb2016-07-21 14:49:33 -07001597 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001598 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001599 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001600 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001601 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001602 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001603
Dan Stoza9e56aa02015-11-02 13:00:03 -08001604 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001605}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001606
Mathias Agopiancd60f992012-08-16 16:28:27 -07001607void SurfaceFlinger::doDebugFlashRegions()
1608{
1609 // is debugging enabled
1610 if (CC_LIKELY(!mDebugRegion))
1611 return;
1612
1613 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001614 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001615 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001616 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001617 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001618 if (!dirtyRegion.isEmpty()) {
1619 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001620 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001621
1622 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001623 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001624 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001625 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1626
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001627 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001628 }
1629 }
1630 }
1631
1632 postFramebuffer();
1633
1634 if (mDebugRegion > 1) {
1635 usleep(mDebugRegion * 1000);
1636 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001637
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001638 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001639 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001640 continue;
1641 }
1642
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001643 status_t result = display->prepareFrame(*getBE().mHwc);
1644 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001645 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001646 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647}
1648
Adrian Roos1e1a1282017-11-01 19:05:31 +01001649void SurfaceFlinger::doTracing(const char* where) {
1650 ATRACE_CALL();
1651 ATRACE_NAME(where);
1652 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001653 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001654 }
1655}
1656
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001657void SurfaceFlinger::logLayerStats() {
1658 ATRACE_CALL();
1659 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001660 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001661 if (display->isPrimary()) {
1662 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001663 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001664 }
1665 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001666
1667 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001668 }
1669}
1670
Lloyd Pique074e8122018-07-26 12:57:23 -07001671void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001672{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001673 ATRACE_CALL();
1674 ALOGV("preComposition");
1675
Mathias Agopiancd60f992012-08-16 16:28:27 -07001676 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001677 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001678 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001679 needExtraInvalidate = true;
1680 }
Robert Carr2047fae2016-11-28 14:09:09 -08001681 });
1682
Mathias Agopiancd60f992012-08-16 16:28:27 -07001683 if (needExtraInvalidate) {
1684 signalLayerUpdate();
1685 }
1686}
1687
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001688void SurfaceFlinger::updateCompositorTiming(
1689 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1690 std::shared_ptr<FenceTime>& presentFenceTime) {
1691 // Update queue of past composite+present times and determine the
1692 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001693 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001694 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001695 while (!getBE().mCompositePresentTimes.empty()) {
1696 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 // Cached values should have been updated before calling this method,
1698 // which helps avoid duplicate syscalls.
1699 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1700 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1701 break;
1702 }
1703 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001704 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001705 }
1706
1707 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001708 while (getBE().mCompositePresentTimes.size() > 16) {
1709 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 }
1711
Brian Andersond0010582017-03-07 13:20:31 -08001712 setCompositorTimingSnapped(
1713 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1714}
1715
1716void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1717 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001718 // Integer division and modulo round toward 0 not -inf, so we need to
1719 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001720 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1722 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1723
Brian Andersond0010582017-03-07 13:20:31 -08001724 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1725 if (idealLatency <= 0) {
1726 idealLatency = vsyncInterval;
1727 }
1728
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001729 // Snap the latency to a value that removes scheduling jitter from the
1730 // composition and present times, which often have >1ms of jitter.
1731 // Reducing jitter is important if an app attempts to extrapolate
1732 // something (such as user input) to an accurate diasplay time.
1733 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1734 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001735 nsecs_t bias = vsyncInterval / 2;
1736 int64_t extraVsyncs =
1737 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1738 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1739 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001740
David Sodman99974d22017-11-28 12:04:33 -08001741 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1742 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1743 getBE().mCompositorTiming.interval = vsyncInterval;
1744 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001745}
1746
Lloyd Pique074e8122018-07-26 12:57:23 -07001747void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001748{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001749 ATRACE_CALL();
1750 ALOGV("postComposition");
1751
Brian Anderson3546a3f2016-07-14 11:51:14 -07001752 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001753 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001754 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001755 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001756 }
1757
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001758 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001759 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001760
David Sodman73beded2017-11-15 11:56:06 -08001761 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001763 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001764 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001765 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001766 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001767 } else {
1768 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1769 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001770
David Sodman73beded2017-11-15 11:56:06 -08001771 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001772 mPreviousPresentFence =
1773 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1774 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001775 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001776
Lloyd Pique41be5d22018-06-21 13:11:48 -07001777 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1778 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001779
Lloyd Pique074e8122018-07-26 12:57:23 -07001780 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001781 // when we started doing work for this frame, but that should be okay
1782 // since updateCompositorTiming has snapping logic.
1783 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001784 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001785 CompositorTiming compositorTiming;
1786 {
David Sodman99974d22017-11-28 12:04:33 -08001787 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1788 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001789 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001790
Robert Carr2047fae2016-11-28 14:09:09 -08001791 mDrawingState.traverseInZOrder([&](Layer* layer) {
1792 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001793 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001794 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001795 recordBufferingStats(layer->getName().string(),
1796 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001797 }
Robert Carr2047fae2016-11-28 14:09:09 -08001798 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001799
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001800 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001801 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001802 enableHardwareVsync();
1803 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001804 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001805 }
1806 }
1807
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001808 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001809 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001810 enableHardwareVsync();
1811 }
1812 }
1813
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001814 if (mAnimCompositionPending) {
1815 mAnimCompositionPending = false;
1816
Brian Anderson4e606e32017-03-16 15:34:57 -07001817 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001818 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001819 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001820 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001821 // The HWC doesn't support present fences, so use the refresh
1822 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001823 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001824 mAnimFrameTracker.setActualPresentTime(presentTime);
1825 }
1826 mAnimFrameTracker.advanceFrame();
1827 }
Dan Stozab90cf072015-03-05 11:05:59 -08001828
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001829 mTimeStats.incrementTotalFrames();
1830 if (mHadClientComposition) {
1831 mTimeStats.incrementClientCompositionFrames();
1832 }
1833
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001834 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001835 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001836 return;
1837 }
1838
1839 nsecs_t currentTime = systemTime();
1840 if (mHasPoweredOff) {
1841 mHasPoweredOff = false;
1842 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001843 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001845 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1846 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001847 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001848 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001849 }
David Sodman4a36e932017-11-07 14:29:47 -08001850 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001851 }
David Sodman4a36e932017-11-07 14:29:47 -08001852 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001853
1854 {
1855 std::lock_guard lock(mTexturePoolMutex);
1856 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1857 if (refillCount > 0) {
1858 const size_t offset = mTexturePool.size();
1859 mTexturePool.resize(mTexturePoolSize);
1860 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1861 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1862 }
1863 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864}
1865
1866void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001867 ATRACE_CALL();
1868 ALOGV("rebuildLayerStacks");
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001871 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001872 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001873 mVisibleRegionsDirty = false;
1874 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001875
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001876 for (const auto& pair : mDisplays) {
1877 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001878 Region opaqueRegion;
1879 Region dirtyRegion;
1880 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001881 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001882 const Transform& tr = display->getTransform();
1883 const Rect bounds = display->getBounds();
1884 if (display->isPoweredOn()) {
1885 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001886
Jeff Sharkey76488112017-02-27 14:15:18 -07001887 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001888 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001889 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001890 Region drawRegion(tr.transform(
1891 layer->visibleNonTransparentRegion));
1892 drawRegion.andSelf(bounds);
1893 if (!drawRegion.isEmpty()) {
1894 layersSortedByZ.add(layer);
1895 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001896 // Clear out the HWC layer if this layer was
1897 // previously visible, but no longer is
1898 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001899 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001900 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001901 // WM changes display->layerStack upon sleep/awake.
1902 // Here we make sure we delete the HWC layers even if
1903 // WM changed their layer stack.
1904 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001905 }
1906
1907 // If a layer is not going to get a release fence because
1908 // it is invisible, but it is also going to release its
1909 // old buffer, add it to the list of layers needing
1910 // fences.
1911 if (hwcLayerDestroyed) {
1912 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1913 mLayersWithQueuedFrames.cend(), layer);
1914 if (found != mLayersWithQueuedFrames.cend()) {
1915 layersNeedingFences.add(layer);
1916 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001917 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001918 });
1919 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001920 display->setVisibleLayersSortedByZ(layersSortedByZ);
1921 display->setLayersNeedingFences(layersNeedingFences);
1922 display->undefinedRegion.set(bounds);
1923 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1924 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001925 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001926 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001927}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001928
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001929// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001930// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001931// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001932// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001933// The returned HDR data space is one of
1934// - Dataspace::UNKNOWN
1935// - Dataspace::BT2020_HLG
1936// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001937Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1938 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001939 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940 *outHdrDataSpace = Dataspace::UNKNOWN;
1941
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001942 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001943 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 case Dataspace::V0_SCRGB:
1945 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001946 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001947 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001948 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001949 case Dataspace::BT2020_PQ:
1950 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001951 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001953 case Dataspace::BT2020_HLG:
1954 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001955 // When there's mixed PQ content and HLG content, we set the HDR
1956 // data space to be BT2020_PQ and convert HLG to PQ.
1957 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1958 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001959 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001960 break;
1961 default:
1962 break;
1963 }
Romain Guy54f154a2017-10-24 21:40:32 +01001964 }
1965
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001966 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001967}
1968
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001969// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001970void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1971 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001972 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1973 *outMode = ColorMode::NATIVE;
1974 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001975 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001976 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001977 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001978
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001979 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001980 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001981
Peiyong Lindfde5112018-06-05 10:58:41 -07001982 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001983 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001984 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001985 if (isHdr) {
1986 bestDataSpace = hdrDataSpace;
1987 }
1988
Chia-I Wu0d711262018-05-21 15:19:35 -07001989 RenderIntent intent;
1990 switch (mDisplayColorSetting) {
1991 case DisplayColorSetting::MANAGED:
1992 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001993 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001994 break;
1995 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001996 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001997 break;
1998 default: // vendor display color setting
1999 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2000 break;
2001 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002002
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002004}
2005
Lloyd Pique074e8122018-07-26 12:57:23 -07002006void SurfaceFlinger::setUpHWComposer() {
2007 ATRACE_CALL();
2008 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002009
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002010 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002011 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2012 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2013 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002014
2015 // If nothing has changed (!dirty), don't recompose.
2016 // If something changed, but we don't currently have any visible layers,
2017 // and didn't when we last did a composition, then skip it this time.
2018 // The second rule does two things:
2019 // - When all layers are removed from a display, we'll emit one black
2020 // frame, then nothing more until we get new layers.
2021 // - When a display is created with a private layer stack, we won't
2022 // emit any black frames until a layer is added to the layer stack.
2023 bool mustRecompose = dirty && !(empty && wasEmpty);
2024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002025 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002026 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2027 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002028
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002029 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002030
2031 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002032 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002033 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002034 }
2035
Lloyd Pique074e8122018-07-26 12:57:23 -07002036 // build the h/w work list
2037 if (CC_UNLIKELY(mGeometryInvalid)) {
2038 mGeometryInvalid = false;
2039 for (const auto& [token, display] : mDisplays) {
2040 const auto displayId = display->getId();
2041 if (displayId >= 0) {
2042 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2043 for (size_t i = 0; i < currentLayers.size(); i++) {
2044 const auto& layer = currentLayers[i];
2045 if (!layer->hasHwcLayer(displayId)) {
2046 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2047 layer->forceClientComposition(displayId);
2048 continue;
2049 }
2050 }
2051
2052 layer->setGeometry(display, i);
2053 if (mDebugDisableHWC || mDebugRegion) {
2054 layer->forceClientComposition(displayId);
2055 }
2056 }
2057 }
2058 }
2059 }
2060
2061 // Set the per-frame data
2062 for (const auto& [token, display] : mDisplays) {
2063 const auto displayId = display->getId();
2064 if (displayId < 0) {
2065 continue;
2066 }
2067
2068 if (mDrawingState.colorMatrixChanged) {
2069 display->setColorTransform(mDrawingState.colorMatrix);
2070 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2071 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2072 displayId, result);
2073 }
2074 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2075 if (layer->isHdrY410()) {
2076 layer->forceClientComposition(displayId);
2077 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2078 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2079 !display->hasHDR10Support()) {
2080 layer->forceClientComposition(displayId);
2081 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2082 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2083 !display->hasHLGSupport()) {
2084 layer->forceClientComposition(displayId);
2085 }
2086
2087 if (layer->getForceClientComposition(displayId)) {
2088 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2089 layer->setCompositionType(displayId, HWC2::Composition::Client);
2090 continue;
2091 }
2092
2093 layer->setPerFrameData(display);
2094 }
2095
2096 if (hasWideColorDisplay) {
2097 ColorMode colorMode;
2098 Dataspace dataSpace;
2099 RenderIntent renderIntent;
2100 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2101 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2102 }
2103 }
2104
2105 mDrawingState.colorMatrixChanged = false;
2106
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002107 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002109 continue;
2110 }
2111
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002112 status_t result = display->prepareFrame(*getBE().mHwc);
2113 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002114 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002115 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002116}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002117
Mathias Agopiancd60f992012-08-16 16:28:27 -07002118void SurfaceFlinger::doComposition() {
2119 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 ALOGV("doComposition");
2121
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002122 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002123 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002124 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002125 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002126 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002127
2128 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002129 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002130
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002131 display->dirtyRegion.clear();
2132 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002133 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002134 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002135 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002136}
2137
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002138void SurfaceFlinger::postFramebuffer()
2139{
Mathias Agopian841cde52012-03-01 15:44:37 -08002140 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002141 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002142
Mathias Agopiana44b0412011-10-16 18:46:35 -07002143 const nsecs_t now = systemTime();
2144 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002145
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002146 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002147 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002148 continue;
2149 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002150 const auto displayId = display->getId();
2151 if (displayId >= 0) {
2152 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002153 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002154 display->onSwapBuffersCompleted();
2155 display->makeCurrent();
2156 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002157 sp<Fence> releaseFence = Fence::NO_FENCE;
2158
Chia-I Wu7b549592017-11-15 09:14:57 -08002159 // The layer buffer from the previous frame (if any) is released
2160 // by HWC only when the release fence from this frame (if any) is
2161 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002162 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002163 if (displayId >= 0) {
2164 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2165 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002166
2167 // If the layer was client composited in the previous frame, we
2168 // need to merge with the previous client target acquire fence.
2169 // Since we do not track that, always merge with the current
2170 // client target acquire fence when it is available, even though
2171 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002172 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002173 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002174 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002175 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002176
David Sodmanb8af7922017-12-21 15:17:55 -08002177 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002178 }
Chia-I Wu83806892017-11-16 10:50:20 -08002179
2180 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002181 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002182 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002183 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002184 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002185 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002186 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002187 }
2188 }
2189
Dominik Laskowski7e045462018-05-30 13:02:02 -07002190 if (displayId >= 0) {
2191 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002192 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002193 }
2194
Mathias Agopiana44b0412011-10-16 18:46:35 -07002195 mLastSwapBufferTime = systemTime() - now;
2196 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002197
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002198 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002199 const auto display = getDefaultDisplayDeviceLocked();
2200 if (display && getHwComposer().isConnected(display->getId())) {
2201 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002202 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2203 logFrameStats();
2204 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002205 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002206}
2207
Mathias Agopian87baae12012-07-31 12:38:26 -07002208void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002209{
Mathias Agopian841cde52012-03-01 15:44:37 -08002210 ATRACE_CALL();
2211
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002212 // here we keep a copy of the drawing state (that is the state that's
2213 // going to be overwritten by handleTransactionLocked()) outside of
2214 // mStateLock so that the side-effects of the State assignment
2215 // don't happen with mStateLock held (which can cause deadlocks).
2216 State drawingState(mDrawingState);
2217
Mathias Agopianca4d3602011-05-19 15:38:14 -07002218 Mutex::Autolock _l(mStateLock);
2219 const nsecs_t now = systemTime();
2220 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002221
Mathias Agopianca4d3602011-05-19 15:38:14 -07002222 // Here we're guaranteed that some transaction flags are set
2223 // so we can call handleTransactionLocked() unconditionally.
2224 // We call getTransactionFlags(), which will also clear the flags,
2225 // with mStateLock held to guarantee that mCurrentState won't change
2226 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002227
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002228 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002229 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002230 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002231
Mathias Agopianca4d3602011-05-19 15:38:14 -07002232 mLastTransactionTime = systemTime() - now;
2233 mDebugInTransaction = 0;
2234 invalidateHwcGeometry();
2235 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002236}
2237
Dominik Laskowski7e045462018-05-30 13:02:02 -07002238DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002239 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002240 // Figure out whether the event is for the primary display or an
2241 // external display by matching the Hwc display id against one for a
2242 // connected display. If we did not find a match, we then check what
2243 // displays are not already connected to determine the type. If we don't
2244 // have a connected primary display, we assume the new display is meant to
2245 // be the primary display, and then if we don't have an external display,
2246 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2248 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002249 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002251 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002252 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002253 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002254 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002255 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002256 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002257 return DisplayDevice::DISPLAY_EXTERNAL;
2258 }
2259
2260 return DisplayDevice::DISPLAY_ID_INVALID;
2261}
2262
Lloyd Piqueba04e622017-12-14 17:11:26 -08002263void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2264 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002265 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002266 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002267 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002268 continue;
2269 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002270
2271 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2272 ALOGE("External displays are not supported by the vr hardware composer.");
2273 continue;
2274 }
2275
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002276 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002277 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002278 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002279 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002280 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002281
2282 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002284 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002286 DisplayDeviceState info;
2287 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002288 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2289 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002290 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002291 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002292 mInterceptor->saveDisplayCreation(info);
2293 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002294 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002295 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002296
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002297 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002298 if (idx >= 0) {
2299 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002300 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002301 mCurrentState.displays.removeItemsAt(idx);
2302 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002303 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002304 }
2305
2306 processDisplayChangesLocked();
2307 }
2308
2309 mPendingHotplugEvents.clear();
2310}
2311
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002313 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002316 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002317 HdrCapabilities hdrCapabilities;
2318 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002319
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002320 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002323 if (isWideColorMode(colorMode)) {
2324 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002326
Dominik Laskowski7e045462018-05-30 13:02:02 -07002327 std::vector<RenderIntent> renderIntents =
2328 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002329 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002330 }
tangrobin6753a022018-08-10 10:58:54 +08002331 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002332
tangrobin6753a022018-08-10 10:58:54 +08002333 if (displayId >= 0) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002334 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2335 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2336 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337
2338 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2339 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2340
2341 /*
2342 * Create our display's surface
2343 */
2344 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2345 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002346 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002347 renderSurface->setNativeWindow(nativeWindow.get());
2348 const int displayWidth = renderSurface->queryWidth();
2349 const int displayHeight = renderSurface->queryHeight();
2350
2351 // Make sure that composition can never be stalled by a virtual display
2352 // consumer that isn't processing buffers fast enough. We have to do this
2353 // in two places:
2354 // * Here, in case the display is composed entirely by HWC.
2355 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2356 // window's swap interval in eglMakeCurrent, so they'll override the
2357 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002358 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002359 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2360 }
2361
2362 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002363 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002364
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002366 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2367 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2368 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002369 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370
2371 if (maxFrameBufferAcquiredBuffers >= 3) {
2372 nativeWindowSurface->preallocateBuffers();
2373 }
2374
2375 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002376 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2377 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002379 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002380 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002382 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002383 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002384 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002385 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002386 display->setLayerStack(state.layerStack);
2387 display->setProjection(state.orientation, state.viewport, state.frame);
2388 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002390 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391}
2392
Lloyd Pique347200f2017-12-14 17:00:15 -08002393void SurfaceFlinger::processDisplayChangesLocked() {
2394 // here we take advantage of Vector's copy-on-write semantics to
2395 // improve performance by skipping the transaction entirely when
2396 // know that the lists are identical
2397 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2398 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2399 if (!curr.isIdenticalTo(draw)) {
2400 mVisibleRegionsDirty = true;
2401 const size_t cc = curr.size();
2402 size_t dc = draw.size();
2403
2404 // find the displays that were removed
2405 // (ie: in drawing state but not in current state)
2406 // also handle displays that changed
2407 // (ie: displays that are in both lists)
2408 for (size_t i = 0; i < dc;) {
2409 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2410 if (j < 0) {
2411 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002412 // Call makeCurrent() on the primary display so we can
2413 // be sure that nothing associated with this display
2414 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2416 defaultDisplay->makeCurrent();
2417 }
2418 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2419 display->disconnect(getHwComposer());
2420 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002421 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2422 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2423 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2424 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2425 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002426 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002427 } else {
2428 // this display is in both lists. see if something changed.
2429 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002430 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2432 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2433 if (state_binder != draw_binder) {
2434 // changing the surface is like destroying and
2435 // recreating the DisplayDevice, so we just remove it
2436 // from the drawing state, so that it get re-added
2437 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2439 display->disconnect(getHwComposer());
2440 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002441 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 mDrawingState.displays.removeItemsAt(i);
2443 dc--;
2444 // at this point we must loop to the next item
2445 continue;
2446 }
2447
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002448 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002449 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002450 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002451 }
2452 if ((state.orientation != draw[i].orientation) ||
2453 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002455 }
2456 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002457 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002458 }
2459 }
2460 }
2461 ++i;
2462 }
2463
2464 // find displays that were added
2465 // (ie: in current state but not in drawing state)
2466 for (size_t i = 0; i < cc; i++) {
2467 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2468 const DisplayDeviceState& state(curr[i]);
2469
2470 sp<DisplaySurface> dispSurface;
2471 sp<IGraphicBufferProducer> producer;
2472 sp<IGraphicBufferProducer> bqProducer;
2473 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002474 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002475
Dominik Laskowski7e045462018-05-30 13:02:02 -07002476 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002477 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002478 // Virtual displays without a surface are dormant:
2479 // they have external state (layer stack, projection,
2480 // etc.) but no internal state (i.e. a DisplayDevice).
2481 if (state.surface != nullptr) {
2482 // Allow VR composer to use virtual displays.
2483 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2484 int width = 0;
2485 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2486 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2487 int height = 0;
2488 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2489 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2490 int intFormat = 0;
2491 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2492 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002493 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002494
Dominik Laskowski7e045462018-05-30 13:02:02 -07002495 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2496 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002497 }
2498
2499 // TODO: Plumb requested format back up to consumer
2500
2501 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002502 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002503 bqProducer, bqConsumer,
2504 state.displayName);
2505
2506 dispSurface = vds;
2507 producer = vds;
2508 }
2509 } else {
2510 ALOGE_IF(state.surface != nullptr,
2511 "adding a supported display, but rendering "
2512 "surface is provided (%p), ignoring it",
2513 state.surface.get());
2514
Dominik Laskowski7e045462018-05-30 13:02:02 -07002515 displayId = state.type;
2516 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002517 producer = bqProducer;
2518 }
2519
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002520 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002522 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002523 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002524 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002525 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002526 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2527 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2528 true);
2529 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2530 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2531 true);
2532 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002533 }
2534 }
2535 }
2536 }
2537 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002538
2539 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002540}
2541
Mathias Agopian87baae12012-07-31 12:38:26 -07002542void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002543{
Dan Stoza7dde5992015-05-22 09:51:44 -07002544 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002545 mCurrentState.traverseInZOrder([](Layer* layer) {
2546 layer->notifyAvailableFrames();
2547 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002548
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549 /*
2550 * Traversal of the children
2551 * (perform the transaction for each of them if needed)
2552 */
2553
Mathias Agopian3559b072012-08-15 13:46:03 -07002554 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002555 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002557 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558
2559 const uint32_t flags = layer->doTransaction(0);
2560 if (flags & Layer::eVisibleRegion)
2561 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002562 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563 }
2564
2565 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002566 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 */
2568
Mathias Agopiane57f2922012-08-09 16:29:12 -07002569 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002570 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002571 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002572 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002574 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002575 // The transform hint might have changed for some layers
2576 // (either because a display has changed, or because a layer
2577 // as changed).
2578 //
2579 // Walk through all the layers in currentLayers,
2580 // and update their transform hint.
2581 //
2582 // If a layer is visible only on a single display, then that
2583 // display is used to calculate the hint, otherwise we use the
2584 // default display.
2585 //
2586 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2587 // the hint is set before we acquire a buffer from the surface texture.
2588 //
2589 // NOTE: layer transactions have taken place already, so we use their
2590 // drawing state. However, SurfaceFlinger's own transaction has not
2591 // happened yet, so we must use the current state layer list
2592 // (soon to become the drawing state list).
2593 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002594 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002595 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002596 bool first = true;
2597 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002598 // NOTE: we rely on the fact that layers are sorted by
2599 // layerStack first (so we don't have to traverse the list
2600 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002601 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002602 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002603 currentlayerStack = layerStack;
2604 // figure out if this layerstack is mirrored
2605 // (more than one display) if so, pick the default display,
2606 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002607 hintDisplay = nullptr;
2608 for (const auto& [token, display] : mDisplays) {
2609 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2610 if (hintDisplay) {
2611 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002612 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002613 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002614 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002615 }
2616 }
2617 }
2618 }
Chet Haase91d25932013-04-11 15:24:55 -07002619
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002620 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002621 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2622 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002623
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002624 // could be null when this layer is using a layerStack
2625 // that is not visible on any display. Also can occur at
2626 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002627 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002628 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002629
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002630 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002631 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002632 if (hintDisplay) {
2633 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002634 }
Robert Carr2047fae2016-11-28 14:09:09 -08002635
2636 first = false;
2637 });
Mathias Agopian84300952012-11-21 16:02:13 -08002638 }
2639
2640
Mathias Agopian3559b072012-08-15 13:46:03 -07002641 /*
2642 * Perform our own transaction if needed
2643 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002644
2645 if (mLayersAdded) {
2646 mLayersAdded = false;
2647 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002648 mVisibleRegionsDirty = true;
2649 }
2650
2651 // some layers might have been removed, so
2652 // we need to update the regions they're exposing.
2653 if (mLayersRemoved) {
2654 mLayersRemoved = false;
2655 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002656 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002657 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002658 // this layer is not visible anymore
2659 // TODO: we could traverse the tree from front to back and
2660 // compute the actual visible region
2661 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002662 Region visibleReg;
2663 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002664 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002665 }
Robert Carr2047fae2016-11-28 14:09:09 -08002666 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667 }
2668
2669 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002670
2671 updateCursorAsync();
2672}
2673
2674void SurfaceFlinger::updateCursorAsync()
2675{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002676 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002677 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002678 continue;
2679 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002680
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002681 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2682 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002683 }
2684 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002685}
2686
2687void SurfaceFlinger::commitTransaction()
2688{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002689 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002690 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002691 for (const auto& l : mLayersPendingRemoval) {
2692 recordBufferingStats(l->getName().string(),
2693 l->getOccupancyHistory(true));
2694 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002695 }
2696 mLayersPendingRemoval.clear();
2697 }
2698
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002699 // If this transaction is part of a window animation then the next frame
2700 // we composite should be considered an animation as well.
2701 mAnimCompositionPending = mAnimTransactionPending;
2702
Mathias Agopian4fec8732012-06-29 14:12:52 -07002703 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002704 // clear the "changed" flags in current state
2705 mCurrentState.colorMatrixChanged = false;
2706
Robert Carr1f0a16a2016-10-24 16:27:39 -07002707 mDrawingState.traverseInZOrder([](Layer* layer) {
2708 layer->commitChildList();
2709 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002710 mTransactionPending = false;
2711 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713}
2714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002715void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2716 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002717 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002718 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002719
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002720 Region aboveOpaqueLayers;
2721 Region aboveCoveredLayers;
2722 Region dirty;
2723
Mathias Agopian87baae12012-07-31 12:38:26 -07002724 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725
Robert Carr2047fae2016-11-28 14:09:09 -08002726 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002728 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002729
Jesse Hall01e29052013-02-19 16:13:35 -08002730 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002731 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002732 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002733 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002734
Mathias Agopianab028732010-03-16 16:41:46 -07002735 /*
2736 * opaqueRegion: area of a surface that is fully opaque.
2737 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002738 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002739
2740 /*
2741 * visibleRegion: area of a surface that is visible on screen
2742 * and not fully transparent. This is essentially the layer's
2743 * footprint minus the opaque regions above it.
2744 * Areas covered by a translucent surface are considered visible.
2745 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002747
2748 /*
2749 * coveredRegion: area of a surface that is covered by all
2750 * visible regions above it (which includes the translucent areas).
2751 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002752 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002753
Jesse Halla8026d22012-09-25 13:25:04 -07002754 /*
2755 * transparentRegion: area of a surface that is hinted to be completely
2756 * transparent. This is only used to tell when the layer has no visible
2757 * non-transparent regions and can be removed from the layer list. It
2758 * does not affect the visibleRegion of this layer or any layers
2759 * beneath it. The hint may not be correct if apps don't respect the
2760 * SurfaceView restrictions (which, sadly, some don't).
2761 */
2762 Region transparentRegion;
2763
Mathias Agopianab028732010-03-16 16:41:46 -07002764
2765 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002766 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002767 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002771 if (!visibleRegion.isEmpty()) {
2772 // Remove the transparent area from the visible region
2773 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002774 if (tr.preserveRects()) {
2775 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002776 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002777 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002778 // transformation too complex, can't do the
2779 // transparent region optimization.
2780 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002781 }
Mathias Agopianab028732010-03-16 16:41:46 -07002782 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783
Mathias Agopianab028732010-03-16 16:41:46 -07002784 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002785 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002786 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002787 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2788 // the opaque region is the layer's footprint
2789 opaqueRegion = visibleRegion;
2790 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002791 }
2792 }
2793
Robert Carre5f4f692018-01-12 13:12:28 -08002794 if (visibleRegion.isEmpty()) {
2795 layer->clearVisibilityRegions();
2796 return;
2797 }
2798
Mathias Agopianab028732010-03-16 16:41:46 -07002799 // Clip the covered region to the visible region
2800 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2801
2802 // Update aboveCoveredLayers for next (lower) layer
2803 aboveCoveredLayers.orSelf(visibleRegion);
2804
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002805 // subtract the opaque region covered by the layers above us
2806 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
2808 // compute this layer's dirty region
2809 if (layer->contentDirty) {
2810 // we need to invalidate the whole region
2811 dirty = visibleRegion;
2812 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002813 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 layer->contentDirty = false;
2815 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002816 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002817 * the exposed region consists of two components:
2818 * 1) what's VISIBLE now and was COVERED before
2819 * 2) what's EXPOSED now less what was EXPOSED before
2820 *
2821 * note that (1) is conservative, we start with the whole
2822 * visible region but only keep what used to be covered by
2823 * something -- which mean it may have been exposed.
2824 *
2825 * (2) handles areas that were not covered by anything but got
2826 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002827 */
Mathias Agopianab028732010-03-16 16:41:46 -07002828 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002829 const Region oldVisibleRegion = layer->visibleRegion;
2830 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002831 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2832 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 }
2834 dirty.subtractSelf(aboveOpaqueLayers);
2835
2836 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002837 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838
Mathias Agopianab028732010-03-16 16:41:46 -07002839 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002841
Jesse Halla8026d22012-09-25 13:25:04 -07002842 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 layer->setVisibleRegion(visibleRegion);
2844 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002845 layer->setVisibleNonTransparentRegion(
2846 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002847 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848
Mathias Agopian87baae12012-07-31 12:38:26 -07002849 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850}
2851
Chia-I Wuab0c3192017-08-01 11:29:00 -07002852void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002853 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002854 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2855 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002856 }
2857 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002858}
2859
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002861{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002862 ALOGV("handlePageFlip");
2863
Brian Andersond6927fb2016-07-23 23:37:30 -07002864 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002865
Mathias Agopian4fec8732012-06-29 14:12:52 -07002866 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002867 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002868 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002869
2870 // Store the set of layers that need updates. This set must not change as
2871 // buffers are being latched, as this could result in a deadlock.
2872 // Example: Two producers share the same command stream and:
2873 // 1.) Layer 0 is latched
2874 // 2.) Layer 0 gets a new frame
2875 // 2.) Layer 1 gets a new frame
2876 // 3.) Layer 1 is latched.
2877 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2878 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002879 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002880 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002881 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002882 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002883 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002884 } else {
2885 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002886 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002887 } else {
2888 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002889 }
Robert Carr2047fae2016-11-28 14:09:09 -08002890 });
2891
Dan Stoza9e56aa02015-11-02 13:00:03 -08002892 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002893 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002894 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002895 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002896 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002897 newDataLatched = true;
2898 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002899 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002900
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002901 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002902
2903 // If we will need to wake up at some time in the future to deal with a
2904 // queued frame that shouldn't be displayed during this vsync period, wake
2905 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002906 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002907 signalLayerUpdate();
2908 }
2909
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002910 // enter boot animation on first buffer latch
2911 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2912 ALOGI("Enter boot animation");
2913 mBootStage = BootStage::BOOTANIMATION;
2914 }
2915
Dan Stoza6b9454d2014-11-07 16:00:59 -08002916 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002917 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918}
2919
Mathias Agopianad456f92011-01-13 17:53:01 -08002920void SurfaceFlinger::invalidateHwcGeometry()
2921{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002922 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002923}
2924
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002925void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2926 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002927 // We only need to actually compose the display if:
2928 // 1) It is being handled by hardware composer, which may need this to
2929 // keep its virtual display state machine in sync, or
2930 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002931 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002932 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002933 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002934 return;
2935 }
2936
Dan Stoza9e56aa02015-11-02 13:00:03 -08002937 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002938 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002939
2940 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002941 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002942}
2943
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002944bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002945 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002946
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002947 const Region bounds(display->bounds());
2948 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002949 const auto displayId = display->getId();
2950 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002951 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002952
Chia-I Wu8e50e692018-05-04 10:12:37 -07002953 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002954 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002955
Dan Stoza9e56aa02015-11-02 13:00:03 -08002956 if (hasClientComposition) {
2957 ALOGV("hasClientComposition");
2958
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002959 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002960 if (display->hasWideColorGamut()) {
2961 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002962 }
2963 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002964 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002965 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002966
Dominik Laskowski7e045462018-05-30 13:02:02 -07002967 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002968 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2969 HWC2::Capability::SkipClientColorTransform);
2970
Chia-I Wud49d6692018-06-27 07:17:41 +08002971 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002972 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2973 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002974 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002975 }
2976
Chia-I Wud49d6692018-06-27 07:17:41 +08002977 // The current enhanced saturation matrix is designed to enhance Display P3,
2978 // thus we only apply this matrix when the render intent is not colorimetric
2979 // and the output color space is Display P3.
2980 needsEnhancedColorMatrix =
2981 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2982 outputDataspace == Dataspace::DISPLAY_P3);
2983 if (needsEnhancedColorMatrix) {
2984 colorMatrix *= mEnhancedSaturationMatrix;
2985 }
2986
2987 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002988
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002989 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002990 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002991 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002992 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002993
2994 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002995 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2996 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2997 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002998 }
2999 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08003000 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003001
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003002 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003003 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003004 // when using overlays, we assume a fully transparent framebuffer
3005 // NOTE: we could reduce how much we need to clear, for instance
3006 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003007 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003008 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003009 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003010 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003011 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003012 // we're left with the letterbox region
3013 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003014 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003015
3016 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003017 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003018
Mathias Agopianb9494d52012-04-18 02:28:45 -07003019 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003020 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003021 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003022 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003023 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003024 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003026 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003027 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003028 // scissor on the main display. It should never be needed
3029 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003030 const Rect& bounds = display->getBounds();
3031 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003032 if (scissor != bounds) {
3033 // scissor doesn't match the screen's dimensions, so we
3034 // need to clear everything outside of it and enable
3035 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003036
Mathias Agopianf45c5102012-10-24 16:29:17 -07003037 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003038 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003039 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003040 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003041 }
3042 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003043 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003044
Mathias Agopian85d751c2012-08-29 16:59:24 -07003045 /*
3046 * and then, render the layers targeted at the framebuffer
3047 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003048
Dan Stoza9e56aa02015-11-02 13:00:03 -08003049 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003050 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003051 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003052 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003053 const Region clip(bounds.intersect(
3054 displayTransform.transform(layer->visibleRegion)));
3055 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003056 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003057 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003058 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003059 case HWC2::Composition::Cursor:
3060 case HWC2::Composition::Device:
3061 case HWC2::Composition::Sideband:
3062 case HWC2::Composition::SolidColor: {
3063 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003064 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303065 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3066 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003067 // never clear the very first layer since we're
3068 // guaranteed the FB is already cleared
3069 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003070 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003071 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003072 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003073 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003074 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003075 break;
3076 }
3077 default:
3078 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003079 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003080 } else {
3081 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003082 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003083 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003084 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003085
Chia-I Wud49d6692018-06-27 07:17:41 +08003086 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003087 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003088 }
3089
Mathias Agopianf45c5102012-10-24 16:29:17 -07003090 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003091 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003092 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003093}
3094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003095void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3096 const Region& region) const {
3097 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003098 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003099 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003100}
3101
Dan Stoza7d89d062015-04-30 13:29:25 -07003102status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003103 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003104 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003105 const sp<Layer>& lbc,
3106 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003107{
Dan Stoza7d89d062015-04-30 13:29:25 -07003108 // add this layer to the current state list
3109 {
3110 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003111 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003112 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3113 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003114 return NO_MEMORY;
3115 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003116 if (parent == nullptr) {
3117 mCurrentState.layersSortedByZ.add(lbc);
3118 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003119 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003120 ALOGE("addClientLayer called with a removed parent");
3121 return NAME_NOT_FOUND;
3122 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003123 parent->addChild(lbc);
3124 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003125
Yiwei Zhang243b3782018-05-15 17:40:04 -07003126 if (gbc != nullptr) {
3127 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3128 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3129 mMaxGraphicBufferProducerListSize,
3130 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3131 mGraphicBufferProducerList.size(),
3132 mMaxGraphicBufferProducerListSize, mNumLayers);
3133 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003134 mLayersAdded = true;
3135 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003136 }
3137
Mathias Agopian96f08192010-06-02 23:28:45 -07003138 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003139 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003140
Dan Stoza7d89d062015-04-30 13:29:25 -07003141 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003142}
3143
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003144status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003145 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003146 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3147}
Robert Carr7f9b8992017-03-10 11:08:39 -08003148
chaviwca27f252018-02-06 16:46:39 -08003149status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3150 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003151 if (layer->isPendingRemoval()) {
3152 return NO_ERROR;
3153 }
3154
Robert Carr1f0a16a2016-10-24 16:27:39 -07003155 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003156 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003157 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003158 if (topLevelOnly) {
3159 return NO_ERROR;
3160 }
3161
Chia-I Wu98f1c102017-05-30 14:54:08 -07003162 sp<Layer> ancestor = p;
3163 while (ancestor->getParent() != nullptr) {
3164 ancestor = ancestor->getParent();
3165 }
3166 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3167 ALOGE("removeLayer called with a layer whose parent has been removed");
3168 return NAME_NOT_FOUND;
3169 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003170
3171 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003172 } else {
3173 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003174 }
3175
Robert Carr136e2f62017-02-08 17:54:29 -08003176 // As a matter of normal operation, the LayerCleaner will produce a second
3177 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3178 // so we will succeed in promoting it, but it's already been removed
3179 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3180 // otherwise something has gone wrong and we are leaking the layer.
3181 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003182 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3183 layer->getName().string(),
3184 (p != nullptr) ? p->getName().string() : "no-parent");
3185 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003186 } else if (index < 0) {
3187 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003188 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003189
Chia-I Wuc6657022017-08-15 11:18:17 -07003190 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003191 mLayersPendingRemoval.add(layer);
3192 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003193 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003194 setTransactionFlags(eTransactionNeeded);
3195 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196}
3197
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003198uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003199 return android_atomic_release_load(&mTransactionFlags);
3200}
3201
Mathias Agopian3f844832013-08-07 21:24:32 -07003202uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003203 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3204}
3205
Mathias Agopian3f844832013-08-07 21:24:32 -07003206uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003207 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3208}
3209
3210uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3211 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003212 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003213 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003215 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216 }
3217 return old;
3218}
3219
chaviwca27f252018-02-06 16:46:39 -08003220bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3221 for (const ComposerState& state : states) {
3222 // Here we need to check that the interface we're given is indeed
3223 // one of our own. A malicious client could give us a nullptr
3224 // IInterface, or one of its own or even one of our own but a
3225 // different type. All these situations would cause us to crash.
3226 if (state.client == nullptr) {
3227 return true;
3228 }
3229
3230 sp<IBinder> binder = IInterface::asBinder(state.client);
3231 if (binder == nullptr) {
3232 return true;
3233 }
3234
3235 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3236 return true;
3237 }
3238 }
3239 return false;
3240}
3241
Mathias Agopian8b33f032012-07-24 20:43:54 -07003242void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003243 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003244 const Vector<DisplayState>& displays,
3245 uint32_t flags)
3246{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003247 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003248 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003249 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003250
chaviwca27f252018-02-06 16:46:39 -08003251 if (containsAnyInvalidClientState(states)) {
3252 return;
3253 }
3254
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003255 if (flags & eAnimation) {
3256 // For window updates that are part of an animation we must wait for
3257 // previous animation "frames" to be handled.
3258 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003259 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003260 if (CC_UNLIKELY(err != NO_ERROR)) {
3261 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003262 // caller after a few seconds.
3263 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3264 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003265 mAnimTransactionPending = false;
3266 break;
3267 }
3268 }
3269 }
3270
chaviwca27f252018-02-06 16:46:39 -08003271 for (const DisplayState& display : displays) {
3272 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003273 }
3274
chaviwca27f252018-02-06 16:46:39 -08003275 for (const ComposerState& state : states) {
3276 transactionFlags |= setClientStateLocked(state);
3277 }
3278
3279 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3280 // as destroyed should only occur after setting all other states. This is to allow for a
3281 // child re-parent to happen before marking its original parent as destroyed (which would
3282 // then mark the child as destroyed).
3283 for (const ComposerState& state : states) {
3284 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003285 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003286
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003287 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3288 // anyway. This can be used as a flush mechanism for previous async transactions.
3289 // Empty animation transaction can be used to simulate back-pressure, so also force a
3290 // transaction for empty animation transactions.
3291 if (transactionFlags == 0 &&
3292 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003293 transactionFlags = eTransactionNeeded;
3294 }
3295
Mathias Agopian386aa982011-11-07 21:58:03 -08003296 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003297 if (mInterceptor->isEnabled()) {
3298 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003299 }
Irvel468051e2016-06-13 16:44:44 -07003300
Mathias Agopian386aa982011-11-07 21:58:03 -08003301 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003302 const auto start = (flags & eEarlyWakeup)
3303 ? VSyncModulator::TransactionStart::EARLY
3304 : VSyncModulator::TransactionStart::NORMAL;
3305 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003306
3307 // if this is a synchronous transaction, wait for it to take effect
3308 // before returning.
3309 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003310 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003311 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003312 if (flags & eAnimation) {
3313 mAnimTransactionPending = true;
3314 }
3315 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003316 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3317 if (CC_UNLIKELY(err != NO_ERROR)) {
3318 // just in case something goes wrong in SF, return to the
3319 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003320 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3321 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003322 break;
3323 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003324 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003325 }
3326}
3327
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003328uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3329 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3330 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003331
Mathias Agopiane57f2922012-08-09 16:29:12 -07003332 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003333 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3334
3335 const uint32_t what = s.what;
3336 if (what & DisplayState::eSurfaceChanged) {
3337 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3338 state.surface = s.surface;
3339 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003340 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003341 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003342 if (what & DisplayState::eLayerStackChanged) {
3343 if (state.layerStack != s.layerStack) {
3344 state.layerStack = s.layerStack;
3345 flags |= eDisplayTransactionNeeded;
3346 }
3347 }
3348 if (what & DisplayState::eDisplayProjectionChanged) {
3349 if (state.orientation != s.orientation) {
3350 state.orientation = s.orientation;
3351 flags |= eDisplayTransactionNeeded;
3352 }
3353 if (state.frame != s.frame) {
3354 state.frame = s.frame;
3355 flags |= eDisplayTransactionNeeded;
3356 }
3357 if (state.viewport != s.viewport) {
3358 state.viewport = s.viewport;
3359 flags |= eDisplayTransactionNeeded;
3360 }
3361 }
3362 if (what & DisplayState::eDisplaySizeChanged) {
3363 if (state.width != s.width) {
3364 state.width = s.width;
3365 flags |= eDisplayTransactionNeeded;
3366 }
3367 if (state.height != s.height) {
3368 state.height = s.height;
3369 flags |= eDisplayTransactionNeeded;
3370 }
3371 }
3372
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 return flags;
3374}
3375
Robert Carrd4ae7f32018-06-07 16:10:57 -07003376bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3377 IPCThreadState* ipc = IPCThreadState::self();
3378 const int pid = ipc->getCallingPid();
3379 const int uid = ipc->getCallingUid();
Peiyong Line70e1292018-08-09 14:06:58 -07003380
Robert Carrd4ae7f32018-06-07 16:10:57 -07003381 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Peiyong Line70e1292018-08-09 14:06:58 -07003382 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003383 return false;
3384 }
3385 return true;
3386}
3387
chaviwca27f252018-02-06 16:46:39 -08003388uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3389 const layer_state_t& s = composerState.state;
3390 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3391
Mathias Agopian13127d82013-03-05 17:47:11 -08003392 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003393 if (layer == nullptr) {
3394 return 0;
3395 }
3396
3397 if (layer->isPendingRemoval()) {
3398 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3399 return 0;
3400 }
3401
3402 uint32_t flags = 0;
3403
3404 const uint32_t what = s.what;
3405 bool geometryAppliesWithResize =
3406 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003407
3408 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3409 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003410 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003411 layer->pushPendingState();
3412 }
3413
chaviw8b3871a2017-11-01 17:41:01 -07003414 if (what & layer_state_t::ePositionChanged) {
3415 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3416 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003417 }
chaviw8b3871a2017-11-01 17:41:01 -07003418 }
3419 if (what & layer_state_t::eLayerChanged) {
3420 // NOTE: index needs to be calculated before we update the state
3421 const auto& p = layer->getParent();
3422 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003423 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003424 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003425 mCurrentState.layersSortedByZ.removeAt(idx);
3426 mCurrentState.layersSortedByZ.add(layer);
3427 // we need traversal (state changed)
3428 // AND transaction (list changed)
3429 flags |= eTransactionNeeded|eTraversalNeeded;
3430 }
chaviw8b3871a2017-11-01 17:41:01 -07003431 } else {
3432 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003433 flags |= eTransactionNeeded|eTraversalNeeded;
3434 }
3435 }
chaviw8b3871a2017-11-01 17:41:01 -07003436 }
3437 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003438 // NOTE: index needs to be calculated before we update the state
3439 const auto& p = layer->getParent();
3440 if (p == nullptr) {
3441 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3442 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3443 mCurrentState.layersSortedByZ.removeAt(idx);
3444 mCurrentState.layersSortedByZ.add(layer);
3445 // we need traversal (state changed)
3446 // AND transaction (list changed)
3447 flags |= eTransactionNeeded|eTraversalNeeded;
3448 }
3449 } else {
3450 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3451 flags |= eTransactionNeeded|eTraversalNeeded;
3452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 }
3454 }
3455 if (what & layer_state_t::eSizeChanged) {
3456 if (layer->setSize(s.w, s.h)) {
3457 flags |= eTraversalNeeded;
3458 }
3459 }
3460 if (what & layer_state_t::eAlphaChanged) {
3461 if (layer->setAlpha(s.alpha))
3462 flags |= eTraversalNeeded;
3463 }
3464 if (what & layer_state_t::eColorChanged) {
3465 if (layer->setColor(s.color))
3466 flags |= eTraversalNeeded;
3467 }
3468 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003469 // TODO: b/109894387
3470 //
3471 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3472 // rotation. To see the problem observe that if we have a square parent, and a child
3473 // of the same size, then we rotate the child 45 degrees around it's center, the child
3474 // must now be cropped to a non rectangular 8 sided region.
3475 //
3476 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3477 // private API, and the WindowManager only uses rotation in one case, which is on a top
3478 // level layer in which cropping is not an issue.
3479 //
3480 // However given that abuse of rotation matrices could lead to surfaces extending outside
3481 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3482 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3483 // transformations.
3484 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003485 flags |= eTraversalNeeded;
3486 }
3487 if (what & layer_state_t::eTransparentRegionChanged) {
3488 if (layer->setTransparentRegionHint(s.transparentRegion))
3489 flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eFlagsChanged) {
3492 if (layer->setFlags(s.flags, s.mask))
3493 flags |= eTraversalNeeded;
3494 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003495 if (what & layer_state_t::eCropChanged_legacy) {
3496 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003497 flags |= eTraversalNeeded;
3498 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003499 if (what & layer_state_t::eFinalCropChanged_legacy) {
3500 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003501 flags |= eTraversalNeeded;
3502 }
3503 if (what & layer_state_t::eLayerStackChanged) {
3504 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3505 // We only allow setting layer stacks for top level layers,
3506 // everything else inherits layer stack from its parent.
3507 if (layer->hasParent()) {
3508 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3509 layer->getName().string());
3510 } else if (idx < 0) {
3511 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3512 "that also does not appear in the top level layer list. Something"
3513 " has gone wrong.", layer->getName().string());
3514 } else if (layer->setLayerStack(s.layerStack)) {
3515 mCurrentState.layersSortedByZ.removeAt(idx);
3516 mCurrentState.layersSortedByZ.add(layer);
3517 // we need traversal (state changed)
3518 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003519 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003520 }
3521 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003522 if (what & layer_state_t::eDeferTransaction_legacy) {
3523 if (s.barrierHandle_legacy != nullptr) {
3524 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3525 } else if (s.barrierGbp_legacy != nullptr) {
3526 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003527 if (authenticateSurfaceTextureLocked(gbp)) {
3528 const auto& otherLayer =
3529 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003530 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003531 } else {
3532 ALOGE("Attempt to defer transaction to to an"
3533 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003534 }
3535 }
chaviw8b3871a2017-11-01 17:41:01 -07003536 // We don't trigger a traversal here because if no other state is
3537 // changed, we don't want this to cause any more work
3538 }
3539 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003540 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003541 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003542 if (!hadParent) {
3543 mCurrentState.layersSortedByZ.remove(layer);
3544 }
chaviw8b3871a2017-11-01 17:41:01 -07003545 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003546 }
chaviw8b3871a2017-11-01 17:41:01 -07003547 }
3548 if (what & layer_state_t::eReparentChildren) {
3549 if (layer->reparentChildren(s.reparentHandle)) {
3550 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003551 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003552 }
chaviw8b3871a2017-11-01 17:41:01 -07003553 if (what & layer_state_t::eDetachChildren) {
3554 layer->detachChildren();
3555 }
3556 if (what & layer_state_t::eOverrideScalingModeChanged) {
3557 layer->setOverrideScalingMode(s.overrideScalingMode);
3558 // We don't trigger a traversal here because if no other state is
3559 // changed, we don't want this to cause any more work
3560 }
Marissa Wall61c58622018-07-18 10:12:20 -07003561 if (what & layer_state_t::eTransformChanged) {
3562 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3563 }
3564 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3565 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3566 flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eCropChanged) {
3569 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3570 }
3571 if (what & layer_state_t::eBufferChanged) {
3572 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3573 }
3574 if (what & layer_state_t::eAcquireFenceChanged) {
3575 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3576 }
3577 if (what & layer_state_t::eDataspaceChanged) {
3578 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3579 }
3580 if (what & layer_state_t::eHdrMetadataChanged) {
3581 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3582 }
3583 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3584 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3585 }
3586 if (what & layer_state_t::eApiChanged) {
3587 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3588 }
3589 if (what & layer_state_t::eSidebandStreamChanged) {
3590 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3591 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003592 return flags;
3593}
3594
chaviwca27f252018-02-06 16:46:39 -08003595void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3596 const layer_state_t& state = composerState.state;
3597 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3598
3599 sp<Layer> layer(client->getLayerUser(state.surface));
3600 if (layer == nullptr) {
3601 return;
3602 }
3603
3604 if (layer->isPendingRemoval()) {
3605 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3606 return;
3607 }
3608
3609 if (state.what & layer_state_t::eDestroySurface) {
3610 removeLayerLocked(mStateLock, layer);
3611 }
3612}
3613
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003615 const String8& name,
3616 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003617 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003618 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003619 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003620{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003621 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003622 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003623 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003624 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003625 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003626
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003627 status_t result = NO_ERROR;
3628
3629 sp<Layer> layer;
3630
Cody Northropbc755282017-03-31 12:00:08 -06003631 String8 uniqueName = getUniqueLayerName(name);
3632
Mathias Agopian3165cc22012-08-08 19:42:09 -07003633 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003634 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003635 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3636 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003637
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003639 case ISurfaceComposerClient::eFXSurfaceBufferState:
3640 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3641 break;
chaviw13fdc492017-06-27 12:40:18 -07003642 case ISurfaceComposerClient::eFXSurfaceColor:
3643 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003644 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003645 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003646 break;
3647 default:
3648 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003649 break;
3650 }
3651
Dan Stoza7d89d062015-04-30 13:29:25 -07003652 if (result != NO_ERROR) {
3653 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003655
Chia-I Wuab0c3192017-08-01 11:29:00 -07003656 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3657 // TODO b/64227542
3658 if (windowType == 441731) {
3659 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3660 layer->setPrimaryDisplayOnly();
3661 }
3662
Albert Chaulk479c60c2017-01-27 14:21:34 -05003663 layer->setInfo(windowType, ownerUid);
3664
Robert Carr1f0a16a2016-10-24 16:27:39 -07003665 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003666 if (result != NO_ERROR) {
3667 return result;
3668 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003669 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003670
3671 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003672 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003673}
3674
Cody Northropbc755282017-03-31 12:00:08 -06003675String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3676{
3677 bool matchFound = true;
3678 uint32_t dupeCounter = 0;
3679
3680 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3681 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3682
Dan Stoza436ccf32018-06-21 12:10:12 -07003683 // Grab the state lock since we're accessing mCurrentState
3684 Mutex::Autolock lock(mStateLock);
3685
Cody Northropbc755282017-03-31 12:00:08 -06003686 // Loop over layers until we're sure there is no matching name
3687 while (matchFound) {
3688 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003689 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003690 if (layer->getName() == uniqueName) {
3691 matchFound = true;
3692 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3693 }
3694 });
3695 }
3696
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003697 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3698 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003699
3700 return uniqueName;
3701}
3702
Marissa Wallfd668622018-05-10 10:21:13 -07003703status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3704 uint32_t w, uint32_t h, uint32_t flags,
3705 PixelFormat& format, sp<IBinder>* handle,
3706 sp<IGraphicBufferProducer>* gbp,
3707 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003708 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003709 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003710 case PIXEL_FORMAT_TRANSPARENT:
3711 case PIXEL_FORMAT_TRANSLUCENT:
3712 format = PIXEL_FORMAT_RGBA_8888;
3713 break;
3714 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003715 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 break;
3717 }
3718
Marissa Wallfd668622018-05-10 10:21:13 -07003719 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3720 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003721 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003722 *handle = layer->getHandle();
3723 *gbp = layer->getProducer();
3724 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003726
Marissa Wallfd668622018-05-10 10:21:13 -07003727 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003728 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729}
3730
Marissa Wall61c58622018-07-18 10:12:20 -07003731status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3732 uint32_t w, uint32_t h, uint32_t flags,
3733 sp<IBinder>* handle, sp<Layer>* outLayer) {
3734 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3735 *handle = layer->getHandle();
3736 *outLayer = layer;
3737
3738 return NO_ERROR;
3739}
3740
chaviw13fdc492017-06-27 12:40:18 -07003741status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003742 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003743 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003744{
chaviw13fdc492017-06-27 12:40:18 -07003745 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003747 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003748}
3749
Mathias Agopianac9fa422013-02-11 16:40:36 -08003750status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003751{
Robert Carr9524cb32017-02-13 11:32:32 -08003752 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003753 status_t err = NO_ERROR;
3754 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003755 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003756 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003757 err = removeLayer(l);
3758 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3759 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003760 }
3761 return err;
3762}
3763
Mathias Agopian13127d82013-03-05 17:47:11 -08003764status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003765{
Mathias Agopian67106042013-03-14 19:18:13 -07003766 // called by ~LayerCleaner() when all references to the IBinder (handle)
3767 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003768 sp<Layer> l = layer.promote();
3769 if (l == nullptr) {
3770 // The layer has already been removed, carry on
3771 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003772 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003773 // If we have a parent, then we can continue to live as long as it does.
3774 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003775}
3776
Mathias Agopianb60314a2012-04-10 22:09:54 -07003777// ---------------------------------------------------------------------------
3778
Andy McFadden13a082e2012-08-24 10:16:42 -07003779void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003780 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3781 if (!displayToken) return;
3782
Jesse Hall01e29052013-02-19 16:13:35 -08003783 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003784 Vector<ComposerState> state;
3785 Vector<DisplayState> displays;
3786 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003787 d.what = DisplayState::eDisplayProjectionChanged |
3788 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003789 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003790 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003791 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003792 d.frame.makeInvalid();
3793 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003794 d.width = 0;
3795 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003796 displays.add(d);
3797 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003798
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003799 const auto display = getDisplayDevice(displayToken);
3800 if (!display) return;
3801
3802 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3803
3804 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003805 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003806 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003807
Brian Andersond0010582017-03-07 13:20:31 -08003808 // Use phase of 0 since phase is not known.
3809 // Use latency of 0, which will snap to the ideal latency.
3810 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003811}
3812
3813void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003814 // Async since we may be called from the main thread.
3815 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003816}
3817
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003818void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3819 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003820 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003821 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003822
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003823 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003824 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003825 return;
3826 }
3827
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003828 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003829 ALOGW("Trying to set power mode for virtual display");
3830 return;
3831 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003832
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003833 display->setPowerMode(mode);
3834
Lloyd Pique4dccc412018-01-22 17:21:36 -08003835 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003836 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003837 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003838 if (idx < 0) {
3839 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3840 return;
3841 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003842 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003843 }
3844
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003845 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003846 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003847 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003848 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003849 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003850 // FIXME: eventthread only knows about the main display right now
3851 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003852 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003853 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003854
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003855 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003856 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003857 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003858
3859 struct sched_param param = {0};
3860 param.sched_priority = 1;
3861 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3862 ALOGW("Couldn't set SCHED_FIFO on display on");
3863 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003864 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003865 // Turn off the display
3866 struct sched_param param = {0};
3867 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3868 ALOGW("Couldn't set SCHED_OTHER on display off");
3869 }
3870
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003871 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003872 disableHardwareVsync(true); // also cancels any in-progress resync
3873
Mathias Agopiancde87a32012-09-13 14:09:01 -07003874 // FIXME: eventthread only knows about the main display right now
3875 mEventThread->onScreenReleased();
3876 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003877
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 getHwComposer().setPowerMode(type, mode);
3879 mVisibleRegionsDirty = true;
3880 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003881 } else if (mode == HWC_POWER_MODE_DOZE ||
3882 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003883 // Update display while dozing
3884 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003885 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003886 // FIXME: eventthread only knows about the main display right now
3887 mEventThread->onScreenAcquired();
3888 resyncToHardwareVsync(true);
3889 }
3890 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3891 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003892 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003893 disableHardwareVsync(true); // also cancels any in-progress resync
3894 // FIXME: eventthread only knows about the main display right now
3895 mEventThread->onScreenReleased();
3896 }
3897 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003898 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003899 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003900 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003901 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003902
3903 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003904}
3905
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003906void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003907 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003908 const auto display = getDisplayDevice(displayToken);
3909 if (!display) {
3910 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3911 displayToken.get());
3912 } else if (display->isVirtual()) {
3913 ALOGW("Attempt to set power mode %d for virtual display", mode);
3914 } else {
3915 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003916 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003917 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003918}
3919
3920// ---------------------------------------------------------------------------
3921
Lloyd Pique755e3192018-01-31 16:46:15 -08003922status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3923 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003925
Mathias Agopianbd115332013-04-18 16:41:04 -07003926 IPCThreadState* ipc = IPCThreadState::self();
3927 const int pid = ipc->getCallingPid();
3928 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003929
Mathias Agopianbd115332013-04-18 16:41:04 -07003930 if ((uid != AID_SHELL) &&
3931 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003932 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003933 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003935 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003936 // (this would indicate SF is stuck, but we want to be able to
3937 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003938 status_t err = mStateLock.timedLock(s2ns(1));
3939 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003940 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003941 result.appendFormat(
3942 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3943 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003944 }
3945
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003946 bool dumpAll = true;
3947 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003948 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003949
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003950 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003951 if ((index < numArgs) &&
3952 (args[index] == String16("--list"))) {
3953 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003954 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003955 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003956 }
3957
3958 if ((index < numArgs) &&
3959 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003960 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003961 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003962 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003963 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003964
3965 if ((index < numArgs) &&
3966 (args[index] == String16("--latency-clear"))) {
3967 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003968 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003969 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003970 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003971
3972 if ((index < numArgs) &&
3973 (args[index] == String16("--dispsync"))) {
3974 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003975 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003976 dumpAll = false;
3977 }
Dan Stozab90cf072015-03-05 11:05:59 -08003978
3979 if ((index < numArgs) &&
3980 (args[index] == String16("--static-screen"))) {
3981 index++;
3982 dumpStaticScreenStats(result);
3983 dumpAll = false;
3984 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003985
3986 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003987 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003988 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003989 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003990 dumpAll = false;
3991 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003992
3993 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3994 index++;
3995 dumpWideColorInfo(result);
3996 dumpAll = false;
3997 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003998
3999 if ((index < numArgs) &&
4000 (args[index] == String16("--enable-layer-stats"))) {
4001 index++;
4002 mLayerStats.enable();
4003 dumpAll = false;
4004 }
4005
4006 if ((index < numArgs) &&
4007 (args[index] == String16("--disable-layer-stats"))) {
4008 index++;
4009 mLayerStats.disable();
4010 dumpAll = false;
4011 }
4012
4013 if ((index < numArgs) &&
4014 (args[index] == String16("--clear-layer-stats"))) {
4015 index++;
4016 mLayerStats.clear();
4017 dumpAll = false;
4018 }
4019
4020 if ((index < numArgs) &&
4021 (args[index] == String16("--dump-layer-stats"))) {
4022 index++;
4023 mLayerStats.dump(result);
4024 dumpAll = false;
4025 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004026
4027 if ((index < numArgs) &&
4028 (args[index] == String16("--display-identification"))) {
4029 index++;
4030 dumpDisplayIdentificationData(result);
4031 dumpAll = false;
4032 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004033
4034 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4035 index++;
4036 mTimeStats.parseArgs(asProto, args, index, result);
4037 dumpAll = false;
4038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004039 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004040
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004041 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004042 if (asProto) {
4043 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4044 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4045 } else {
4046 dumpAllLocked(args, index, result);
4047 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004048 }
4049
Mathias Agopian9795c422009-08-26 16:36:26 -07004050 if (locked) {
4051 mStateLock.unlock();
4052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004053 }
4054 write(fd, result.string(), result.size());
4055 return NO_ERROR;
4056}
4057
Dan Stozac7014012014-02-14 15:03:43 -08004058void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4059 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004060{
Robert Carr2047fae2016-11-28 14:09:09 -08004061 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004062 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004063 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004064}
4065
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004066void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004067 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004068{
4069 String8 name;
4070 if (index < args.size()) {
4071 name = String8(args[index]);
4072 index++;
4073 }
4074
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004075 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4076 getHwComposer().isConnected(displayId)) {
4077 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4078 const nsecs_t period = activeConfig->getVsyncPeriod();
4079 result.appendFormat("%" PRId64 "\n", period);
4080 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004081
4082 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004083 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004084 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004085 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004086 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004087 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004088 }
Robert Carr2047fae2016-11-28 14:09:09 -08004089 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004090 }
4091}
4092
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004093void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004094 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004095{
4096 String8 name;
4097 if (index < args.size()) {
4098 name = String8(args[index]);
4099 index++;
4100 }
4101
Robert Carr2047fae2016-11-28 14:09:09 -08004102 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004103 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004104 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004105 }
Robert Carr2047fae2016-11-28 14:09:09 -08004106 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004107
Svetoslavd85084b2014-03-20 10:28:31 -07004108 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004109}
4110
Jamie Gennis6547ff42013-07-16 20:12:42 -07004111// This should only be called from the main thread. Otherwise it would need
4112// the lock and should use mCurrentState rather than mDrawingState.
4113void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004114 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004115 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004116 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004117
4118 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4119}
4120
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004121void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004122{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004123 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004124
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004125 if (isLayerTripleBufferingDisabled())
4126 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004127
4128 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004129 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004130 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004131 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004132 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4133 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004134 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004135}
4136
Dan Stozab90cf072015-03-05 11:05:59 -08004137void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4138{
4139 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004140 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4141 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004142 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004143 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004144 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4145 b + 1, bucketTimeSec, percent);
4146 }
David Sodman4a36e932017-11-07 14:29:47 -08004147 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004148 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004149 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004150 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004151 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004152}
4153
Dan Stozae77c7662016-05-13 11:37:28 -07004154void SurfaceFlinger::recordBufferingStats(const char* layerName,
4155 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004156 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4157 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004158 for (const auto& segment : history) {
4159 if (!segment.usedThirdBuffer) {
4160 stats.twoBufferTime += segment.totalTime;
4161 }
4162 if (segment.occupancyAverage < 1.0f) {
4163 stats.doubleBufferedTime += segment.totalTime;
4164 } else if (segment.occupancyAverage < 2.0f) {
4165 stats.tripleBufferedTime += segment.totalTime;
4166 }
4167 ++stats.numSegments;
4168 stats.totalTime += segment.totalTime;
4169 }
4170}
4171
Brian Andersond6927fb2016-07-23 23:37:30 -07004172void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4173 result.appendFormat("Layer frame timestamps:\n");
4174
4175 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4176 const size_t count = currentLayers.size();
4177 for (size_t i=0 ; i<count ; i++) {
4178 currentLayers[i]->dumpFrameEvents(result);
4179 }
4180}
4181
Dan Stozae77c7662016-05-13 11:37:28 -07004182void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4183 result.append("Buffering stats:\n");
4184 result.append(" [Layer name] <Active time> <Two buffer> "
4185 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004186 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004187 typedef std::tuple<std::string, float, float, float> BufferTuple;
4188 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004189 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004190 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004191 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004192 if (stats.numSegments == 0) {
4193 continue;
4194 }
4195 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4196 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4197 stats.totalTime;
4198 float doubleBufferRatio = static_cast<float>(
4199 stats.doubleBufferedTime) / stats.totalTime;
4200 float tripleBufferRatio = static_cast<float>(
4201 stats.tripleBufferedTime) / stats.totalTime;
4202 sorted.insert({activeTime, {name, twoBufferRatio,
4203 doubleBufferRatio, tripleBufferRatio}});
4204 }
4205 for (const auto& sortedPair : sorted) {
4206 float activeTime = sortedPair.first;
4207 const BufferTuple& values = sortedPair.second;
4208 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4209 std::get<0>(values).c_str(), activeTime,
4210 std::get<1>(values), std::get<2>(values),
4211 std::get<3>(values));
4212 }
4213 result.append("\n");
4214}
4215
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004216void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004217 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004218 const int32_t displayId = display->getId();
4219 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4220 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004221 continue;
4222 }
4223
Dominik Laskowski7e045462018-05-30 13:02:02 -07004224 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004225 uint8_t port;
4226 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004227 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004228 result.append("no identification data\n");
4229 continue;
4230 }
4231
4232 if (!isEdid(data)) {
4233 result.append("unknown identification data: ");
4234 for (uint8_t byte : data) {
4235 result.appendFormat("%x ", byte);
4236 }
4237 result.append("\n");
4238 continue;
4239 }
4240
4241 const auto edid = parseEdid(data);
4242 if (!edid) {
4243 result.append("invalid EDID: ");
4244 for (uint8_t byte : data) {
4245 result.appendFormat("%x ", byte);
4246 }
4247 result.append("\n");
4248 continue;
4249 }
4250
4251 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4252 result.append(edid->displayName.data(), edid->displayName.length());
4253 result.append("\"\n");
4254 }
4255 result.append("\n");
4256}
4257
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004258void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4259 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004260 result.appendFormat("DisplayColorSetting: %s\n",
4261 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004262
4263 // TODO: print out if wide-color mode is active or not
4264
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004265 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004266 const int32_t displayId = display->getId();
4267 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004268 continue;
4269 }
4270
Dominik Laskowski7e045462018-05-30 13:02:02 -07004271 result.appendFormat("Display %d color modes:\n", displayId);
4272 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004273 for (auto&& mode : modes) {
4274 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4275 }
4276
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004277 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004278 result.appendFormat(" Current color mode: %s (%d)\n",
4279 decodeColorMode(currentMode).c_str(), currentMode);
4280 }
4281 result.append("\n");
4282}
4283
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004284LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004285 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004286 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4287 const State& state = useDrawing ? mDrawingState : mCurrentState;
4288 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004289 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004290 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004291 });
4292
4293 return layersProto;
4294}
4295
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004296LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004297 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004298
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004299 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004300 resolution->set_w(display.getWidth());
4301 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004302
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004303 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4304 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4305 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004306
Dominik Laskowski7e045462018-05-30 13:02:02 -07004307 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004308 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004309 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004310 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004311 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004312 }
4313 });
4314
4315 return layersProto;
4316}
4317
Mathias Agopian74d211a2013-04-22 16:55:35 +02004318void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4319 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004320{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004321 bool colorize = false;
4322 if (index < args.size()
4323 && (args[index] == String16("--color"))) {
4324 colorize = true;
4325 index++;
4326 }
4327
4328 Colorizer colorizer(colorize);
4329
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330 // figure out if we're stuck somewhere
4331 const nsecs_t now = systemTime();
4332 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4333 const nsecs_t inTransaction(mDebugInTransaction);
4334 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4335 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4336
4337 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004338 * Dump library configuration.
4339 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004340
4341 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004342 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004344 appendSfConfigString(result);
4345 appendUiConfigString(result);
4346 appendGuiConfigString(result);
4347 result.append("\n");
4348
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004349 result.append("\nDisplay identification data:\n");
4350 dumpDisplayIdentificationData(result);
4351
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004352 result.append("\nWide-Color information:\n");
4353 dumpWideColorInfo(result);
4354
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004355 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004356 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004357 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004358 result.append(SyncFeatures::getInstance().toString());
4359 result.append("\n");
4360
Andy McFadden41d67d72014-04-25 16:58:34 -07004361 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004362 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004363 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004364
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004365 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4366 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004367 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4368 getHwComposer().isConnected(displayId)) {
4369 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004370 result.appendFormat("Display %d: "
4371 "app phase %" PRId64 " ns, "
4372 "sf phase %" PRId64 " ns, "
4373 "early app phase %" PRId64 " ns, "
4374 "early sf phase %" PRId64 " ns, "
4375 "early app gl phase %" PRId64 " ns, "
4376 "early sf gl phase %" PRId64 " ns, "
4377 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4378 displayId,
4379 vsyncPhaseOffsetNs,
4380 sfVsyncPhaseOffsetNs,
4381 appEarlyOffset,
4382 sfEarlyOffset,
4383 appEarlyGlOffset,
4384 sfEarlyOffset,
4385 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004386 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004387 result.append("\n");
4388
Dan Stozab90cf072015-03-05 11:05:59 -08004389 // Dump static screen stats
4390 result.append("\n");
4391 dumpStaticScreenStats(result);
4392 result.append("\n");
4393
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004394 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4395
Dan Stozae77c7662016-05-13 11:37:28 -07004396 dumpBufferingStats(result);
4397
Andy McFadden4803b742012-09-24 19:07:20 -07004398 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004399 * Dump the visible layer list
4400 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004401 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004402 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004403 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4404 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004405 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004406
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004407 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004408 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004409 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004410 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004411
4412 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004413 * Dump Display state
4414 */
4415
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004417 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004418 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004419 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004420 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004421 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004422 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004423
4424 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004425 * Dump SurfaceFlinger global state
4426 */
4427
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004429 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004430 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004431
Mathias Agopian888c8222012-08-04 21:10:38 -07004432 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004433 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004434
David Sodmanbc815282017-11-05 18:57:52 -08004435 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004436
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004437 if (display) {
4438 display->undefinedRegion.dump(result, "undefinedRegion");
4439 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4440 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004441 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004442 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4443 " last transaction time : %f us\n"
4444 " transaction-flags : %08x\n"
4445 " gpu_to_cpu_unsupported : %d\n",
4446 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4447 mTransactionFlags, !mGpuToCpuSupported);
4448
4449 if (display) {
4450 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4451 result.appendFormat(" refresh-rate : %f fps\n"
4452 " x-dpi : %f\n"
4453 " y-dpi : %f\n",
4454 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4455 activeConfig->getDpiY());
4456 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457
Mathias Agopian74d211a2013-04-22 16:55:35 +02004458 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004459 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004460
Mathias Agopian74d211a2013-04-22 16:55:35 +02004461 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004462 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004463
4464 /*
4465 * VSYNC state
4466 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004467 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004468 result.append("\n");
4469
4470 /*
4471 * HWC layer minidump
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) {
Dan Stozae22aec72016-08-01 13:20:59 -07004476 continue;
4477 }
4478
Dominik Laskowski7e045462018-05-30 13:02:02 -07004479 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004480 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004481 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004482 result.append("\n");
4483 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004484
4485 /*
4486 * Dump HWComposer state
4487 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004488 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004489 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004490 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004491 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004492 result.appendFormat(" h/w composer %s\n",
4493 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004494 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004495
4496 /*
4497 * Dump gralloc state
4498 */
4499 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4500 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004501
4502 /*
4503 * Dump VrFlinger state if in use.
4504 */
4505 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4506 result.append("VrFlinger state:\n");
4507 result.append(mVrFlinger->Dump().c_str());
4508 result.append("\n");
4509 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004510}
4511
Dominik Laskowski7e045462018-05-30 13:02:02 -07004512const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004513 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004514 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004515 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004516 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004517 }
4518 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004519
4520 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4521 static const Vector<sp<Layer>> empty;
4522 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004523}
4524
Keun young Park63f165f2012-08-31 10:53:36 -07004525bool SurfaceFlinger::startDdmConnection()
4526{
4527 void* libddmconnection_dso =
4528 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4529 if (!libddmconnection_dso) {
4530 return false;
4531 }
4532 void (*DdmConnection_start)(const char* name);
4533 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004534 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004535 if (!DdmConnection_start) {
4536 dlclose(libddmconnection_dso);
4537 return false;
4538 }
4539 (*DdmConnection_start)(getServiceName());
4540 return true;
4541}
4542
Chia-I Wu28f320b2018-05-03 11:02:56 -07004543void SurfaceFlinger::updateColorMatrixLocked() {
4544 mat4 colorMatrix;
4545 if (mGlobalSaturationFactor != 1.0f) {
4546 // Rec.709 luma coefficients
4547 float3 luminance{0.213f, 0.715f, 0.072f};
4548 luminance *= 1.0f - mGlobalSaturationFactor;
4549 mat4 saturationMatrix = mat4(
4550 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4551 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4552 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4553 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4554 );
4555 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4556 } else {
4557 colorMatrix = mClientColorMatrix * mDaltonizer();
4558 }
4559
4560 if (mCurrentState.colorMatrix != colorMatrix) {
4561 mCurrentState.colorMatrix = colorMatrix;
4562 mCurrentState.colorMatrixChanged = true;
4563 setTransactionFlags(eTransactionNeeded);
4564 }
4565}
4566
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004567status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Peiyong Line70e1292018-08-09 14:06:58 -07004568 switch (code) {
Ana Krulece2437712018-07-19 17:01:45 -07004569 case CREATE_CONNECTION:
4570 case CREATE_DISPLAY:
Peiyong Line70e1292018-08-09 14:06:58 -07004571 case BOOT_FINISHED:
4572 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulece2437712018-07-19 17:01:45 -07004573 case GET_ANIMATION_FRAME_STATS:
Peiyong Line70e1292018-08-09 14:06:58 -07004574 case SET_POWER_MODE:
Ana Krulece2437712018-07-19 17:01:45 -07004575 case GET_HDR_CAPABILITIES:
Peiyong Line70e1292018-08-09 14:06:58 -07004576 case ENABLE_VSYNC_INJECTIONS:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004577 case INJECT_VSYNC:
Peiyong Line70e1292018-08-09 14:06:58 -07004578 {
4579 // codes that require permission check
Robert Carrd4ae7f32018-06-07 16:10:57 -07004580 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4581 IPCThreadState* ipc = IPCThreadState::self();
4582 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4583 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004584 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004585 }
Peiyong Line70e1292018-08-09 14:06:58 -07004586 break;
4587 }
4588 /*
4589 * Calling setTransactionState is safe, because you need to have been
4590 * granted a reference to Client* and Handle* to do anything with it.
4591 *
4592 * Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4593 */
4594 case SET_TRANSACTION_STATE:
4595 case CREATE_SCOPED_CONNECTION:
4596 {
Robert Carr1db73f62016-12-21 12:58:51 -08004597 return OK;
4598 }
Peiyong Line70e1292018-08-09 14:06:58 -07004599 case CAPTURE_SCREEN:
4600 {
4601 // codes that require permission check
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004602 IPCThreadState* ipc = IPCThreadState::self();
4603 const int pid = ipc->getCallingPid();
4604 const int uid = ipc->getCallingUid();
Peiyong Line70e1292018-08-09 14:06:58 -07004605 if ((uid != AID_GRAPHICS) &&
4606 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4607 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004608 return PERMISSION_DENIED;
4609 }
Peiyong Line70e1292018-08-09 14:06:58 -07004610 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004611 }
Peiyong Line70e1292018-08-09 14:06:58 -07004612 case CAPTURE_LAYERS: {
chaviwa76b2712017-09-20 12:02:26 -07004613 IPCThreadState* ipc = IPCThreadState::self();
4614 const int pid = ipc->getCallingPid();
4615 const int uid = ipc->getCallingUid();
4616 if ((uid != AID_GRAPHICS) &&
4617 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4618 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4619 return PERMISSION_DENIED;
4620 }
Peiyong Line70e1292018-08-09 14:06:58 -07004621 break;
chaviwa76b2712017-09-20 12:02:26 -07004622 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004623 }
Peiyong Line70e1292018-08-09 14:06:58 -07004624 return OK;
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004625}
4626
Peiyong Line70e1292018-08-09 14:06:58 -07004627status_t SurfaceFlinger::onTransact(
4628 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
4629{
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004630 status_t credentialCheck = CheckTransactCodeCredentials(code);
4631 if (credentialCheck != OK) {
4632 return credentialCheck;
4633 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004634
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004635 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4636 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004637 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004638 IPCThreadState* ipc = IPCThreadState::self();
4639 const int uid = ipc->getCallingUid();
4640 if (CC_UNLIKELY(uid != AID_SYSTEM
4641 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004642 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004643 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004644 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004645 return PERMISSION_DENIED;
4646 }
4647 int n;
4648 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004649 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004650 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004651 return NO_ERROR;
4652 case 1002: // SHOW_UPDATES
4653 n = data.readInt32();
4654 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004655 invalidateHwcGeometry();
4656 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004657 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004659 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004660 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004661 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004662 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004663 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004664 setTransactionFlags(
4665 eTransactionNeeded|
4666 eDisplayTransactionNeeded|
4667 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004668 return NO_ERROR;
4669 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004670 case 1006:{ // send empty update
4671 signalRefresh();
4672 return NO_ERROR;
4673 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004674 case 1008: // toggle use of hw composer
4675 n = data.readInt32();
4676 mDebugDisableHWC = n ? 1 : 0;
4677 invalidateHwcGeometry();
4678 repaintEverything();
4679 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004680 case 1009: // toggle use of transform hint
4681 n = data.readInt32();
4682 mDebugDisableTransformHint = n ? 1 : 0;
4683 invalidateHwcGeometry();
4684 repaintEverything();
4685 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004686 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004687 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004688 reply->writeInt32(0);
4689 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004690 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004691 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004692 return NO_ERROR;
4693 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004694 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004695 if (!display) {
4696 return NAME_NOT_FOUND;
4697 }
4698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004699 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004700 return NO_ERROR;
4701 }
4702 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004703 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004704 // daltonize
4705 n = data.readInt32();
4706 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004707 case 1:
4708 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4709 break;
4710 case 2:
4711 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4712 break;
4713 case 3:
4714 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4715 break;
4716 default:
4717 mDaltonizer.setType(ColorBlindnessType::None);
4718 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004719 }
4720 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004721 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004722 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004723 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004724 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004725
4726 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004727 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004728 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004729 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004730 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004731 // apply a color matrix
4732 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004733 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004734 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004735 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004736 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004737 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004738 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004739 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004740 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004741 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004742 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004743
4744 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4745 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004746 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004747 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4748 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4749 }
4750
Chia-I Wu28f320b2018-05-03 11:02:56 -07004751 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004752 return NO_ERROR;
4753 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004754 // This is an experimental interface
4755 // Needs to be shifted to proper binder interface when we productize
4756 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004757 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004758 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004759 return NO_ERROR;
4760 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004761 case 1017: {
4762 n = data.readInt32();
4763 mForceFullDamage = static_cast<bool>(n);
4764 return NO_ERROR;
4765 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004766 case 1018: { // Modify Choreographer's phase offset
4767 n = data.readInt32();
4768 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4769 return NO_ERROR;
4770 }
4771 case 1019: { // Modify SurfaceFlinger's phase offset
4772 n = data.readInt32();
4773 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4774 return NO_ERROR;
4775 }
Irvel468051e2016-06-13 16:44:44 -07004776 case 1020: { // Layer updates interceptor
4777 n = data.readInt32();
4778 if (n) {
4779 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004780 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004781 }
4782 else{
4783 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004784 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004785 }
4786 return NO_ERROR;
4787 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004788 case 1021: { // Disable HWC virtual displays
4789 n = data.readInt32();
4790 mUseHwcVirtualDisplays = !n;
4791 return NO_ERROR;
4792 }
Romain Guy0147a172017-06-01 13:53:56 -07004793 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004794 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004795 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004796
Chia-I Wu28f320b2018-05-03 11:02:56 -07004797 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004798 return NO_ERROR;
4799 }
Romain Guy54f154a2017-10-24 21:40:32 +01004800 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004801 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004802 invalidateHwcGeometry();
4803 repaintEverything();
4804 return NO_ERROR;
4805 }
4806 case 1024: { // Is wide color gamut rendering/color management supported?
4807 reply->writeBool(hasWideColorDisplay);
4808 return NO_ERROR;
4809 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004810 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004811 n = data.readInt32();
4812 if (n) {
4813 ALOGV("LayerTracing enabled");
4814 mTracing.enable();
4815 doTracing("tracing.enable");
4816 reply->writeInt32(NO_ERROR);
4817 } else {
4818 ALOGV("LayerTracing disabled");
4819 status_t err = mTracing.disable();
4820 reply->writeInt32(err);
4821 }
4822 return NO_ERROR;
4823 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004824 case 1026: { // Get layer tracing status
4825 reply->writeBool(mTracing.isEnabled());
4826 return NO_ERROR;
4827 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004828 // Is a DisplayColorSetting supported?
4829 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004830 const auto display = getDefaultDisplayDevice();
4831 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004832 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004833 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004834
4835 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4836 switch (setting) {
4837 case DisplayColorSetting::MANAGED:
4838 reply->writeBool(hasWideColorDisplay);
4839 break;
4840 case DisplayColorSetting::UNMANAGED:
4841 reply->writeBool(true);
4842 break;
4843 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004844 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004845 break;
4846 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004847 reply->writeBool(
4848 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004849 break;
4850 }
4851 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004852 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004853 // Is VrFlinger active?
4854 case 1028: {
4855 Mutex::Autolock _l(mStateLock);
4856 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4857 return NO_ERROR;
4858 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004859 case 1029: {
4860 // Code 1029 is an experimental feature that allows applications to
4861 // simulate a high frequency panel by setting a multiplier and divisor
4862 // on the VSYNC-sf clock. If either the multiplier or divisor are
4863 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4864 // to it's normal frequency.
4865 int multiplier = data.readInt32();
4866 int divisor = data.readInt32();
4867
4868 if ((multiplier == 0) || (divisor == 0)) {
4869 multiplier = 1;
4870 divisor = 1;
4871 }
4872
4873 if ((multiplier == 1) && (divisor == 1)) {
4874 enableHardwareVsync();
4875 } else {
4876 disableHardwareVsync(true);
4877 }
4878 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4879 ->scalePanelFrequency(multiplier, divisor);
4880 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4881
4882 ATRACE_INT("PeriodMultiplier", multiplier);
4883 ATRACE_INT("PeriodDivisor", divisor);
4884 return NO_ERROR;
4885 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004886 }
4887 }
4888 return err;
4889}
4890
Steven Thomas6d8110b2017-08-31 18:24:21 -07004891void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004892 android_atomic_or(1, &mRepaintEverything);
4893 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004894}
4895
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004896// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4897class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004898public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004899 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4900 ~WindowDisconnector() {
4901 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004902 }
4903
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004904private:
4905 ANativeWindow* mWindow;
4906 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004907};
4908
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004909status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4910 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4911 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4912 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004913 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004914 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004915
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004916 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004917
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004918 const auto display = getDisplayDeviceLocked(displayToken);
4919 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004920
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004921 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004922
4923 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004924 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004925 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004926}
4927
4928status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004929 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004930 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004931 ATRACE_CALL();
4932
4933 class LayerRenderArea : public RenderArea {
4934 public:
Robert Carr578038f2018-03-09 12:25:24 -08004935 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4936 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004937 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004938 mLayer(layer),
4939 mCrop(crop),
4940 mFlinger(flinger),
4941 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004942 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004943 Rect getBounds() const override {
4944 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004945 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004946 }
Marissa Wall61c58622018-07-18 10:12:20 -07004947 int getHeight() const override {
4948 return mLayer->getActiveHeight(mLayer->getDrawingState());
4949 }
4950 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004951 bool isSecure() const override { return false; }
4952 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004953 Rect getSourceCrop() const override {
4954 if (mCrop.isEmpty()) {
4955 return getBounds();
4956 } else {
4957 return mCrop;
4958 }
4959 }
Robert Carr578038f2018-03-09 12:25:24 -08004960 class ReparentForDrawing {
4961 public:
4962 const sp<Layer>& oldParent;
4963 const sp<Layer>& newParent;
4964
4965 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4966 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004967 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004968 }
Robert Carr15eae092018-03-23 13:43:53 -07004969 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004970 };
4971
4972 void render(std::function<void()> drawLayers) override {
4973 if (!mChildrenOnly) {
4974 mTransform = mLayer->getTransform().inverse();
4975 drawLayers();
4976 } else {
4977 Rect bounds = getBounds();
4978 screenshotParentLayer =
4979 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
4980 bounds.getWidth(), bounds.getHeight(), 0);
4981
4982 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
4983 drawLayers();
4984 }
4985 }
chaviwa76b2712017-09-20 12:02:26 -07004986
chaviwa76b2712017-09-20 12:02:26 -07004987 private:
chaviw7206d492017-11-10 16:16:12 -08004988 const sp<Layer> mLayer;
4989 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004990
4991 // In the "childrenOnly" case we reparent the children to a screenshot
4992 // layer which has no properties set and which does not draw.
4993 sp<ContainerLayer> screenshotParentLayer;
4994 Transform mTransform;
4995
4996 SurfaceFlinger* mFlinger;
4997 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07004998 };
4999
5000 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5001 auto parent = layerHandle->owner.promote();
5002
chaviw7206d492017-11-10 16:16:12 -08005003 if (parent == nullptr || parent->isPendingRemoval()) {
5004 ALOGE("captureLayers called with a removed parent");
5005 return NAME_NOT_FOUND;
5006 }
5007
Robert Carr578038f2018-03-09 12:25:24 -08005008 const int uid = IPCThreadState::self()->getCallingUid();
5009 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5010 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5011 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5012 return PERMISSION_DENIED;
5013 }
5014
chaviw7206d492017-11-10 16:16:12 -08005015 Rect crop(sourceCrop);
5016 if (sourceCrop.width() <= 0) {
5017 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005018 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005019 }
5020
5021 if (sourceCrop.height() <= 0) {
5022 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005023 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005024 }
5025
5026 int32_t reqWidth = crop.width() * frameScale;
5027 int32_t reqHeight = crop.height() * frameScale;
5028
Robert Carr578038f2018-03-09 12:25:24 -08005029 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005030
Robert Carr578038f2018-03-09 12:25:24 -08005031 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005032 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5033 if (!layer->isVisible()) {
5034 return;
Robert Carr578038f2018-03-09 12:25:24 -08005035 } else if (childrenOnly && layer == parent.get()) {
5036 return;
chaviwa76b2712017-09-20 12:02:26 -07005037 }
5038 visitor(layer);
5039 });
5040 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005041 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005042}
5043
5044status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5045 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005046 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005047 bool useIdentityTransform) {
5048 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005049
Iris Chang7501ed62018-04-30 14:45:42 +08005050 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005051
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005052 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5053 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5054 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5055 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005056
5057 // This mutex protects syncFd and captureResult for communication of the return values from the
5058 // main thread back to this Binder thread
5059 std::mutex captureMutex;
5060 std::condition_variable captureCondition;
5061 std::unique_lock<std::mutex> captureLock(captureMutex);
5062 int syncFd = -1;
5063 std::optional<status_t> captureResult;
5064
Robert Carr03480e22018-01-04 16:02:06 -08005065 const int uid = IPCThreadState::self()->getCallingUid();
5066 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5067
Dominik Laskowski8c001672018-05-30 16:52:06 -07005068 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005069 // If there is a refresh pending, bug out early and tell the binder thread to try again
5070 // after the refresh.
5071 if (mRefreshPending) {
5072 ATRACE_NAME("Skipping screenshot for now");
5073 std::unique_lock<std::mutex> captureLock(captureMutex);
5074 captureResult = std::make_optional<status_t>(EAGAIN);
5075 captureCondition.notify_one();
5076 return;
5077 }
5078
5079 status_t result = NO_ERROR;
5080 int fd = -1;
5081 {
5082 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005083 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005084 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5085 useIdentityTransform, forSystem, &fd);
5086 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005087 }
5088
5089 {
5090 std::unique_lock<std::mutex> captureLock(captureMutex);
5091 syncFd = fd;
5092 captureResult = std::make_optional<status_t>(result);
5093 captureCondition.notify_one();
5094 }
5095 });
5096
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005097 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005098 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005099 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005100 while (*captureResult == EAGAIN) {
5101 captureResult.reset();
5102 result = postMessageAsync(message);
5103 if (result != NO_ERROR) {
5104 return result;
5105 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005106 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005107 }
5108 result = *captureResult;
5109 }
5110
5111 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005112 sync_wait(syncFd, -1);
5113 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005114 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005115
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005116 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005117}
5118
chaviwa76b2712017-09-20 12:02:26 -07005119void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5120 TraverseLayersFunction traverseLayers, bool yswap,
5121 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005122 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005123
Lloyd Pique144e1162017-12-20 16:44:52 -08005124 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005125
5126 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005127 const auto raWidth = renderArea.getWidth();
5128 const auto raHeight = renderArea.getHeight();
5129
5130 const auto reqWidth = renderArea.getReqWidth();
5131 const auto reqHeight = renderArea.getReqHeight();
5132 Rect sourceCrop = renderArea.getSourceCrop();
5133
Iris Chang7501ed62018-04-30 14:45:42 +08005134 bool filtering = false;
5135 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5136 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5137 static_cast<int32_t>(reqHeight) != raWidth;
5138 } else {
5139 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5140 static_cast<int32_t>(reqHeight) != raHeight;
5141 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005142
Dan Stozac1879002014-05-22 15:59:05 -07005143 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005144 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005145 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005146 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005147 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5148 Transform tr;
5149 uint32_t flags = 0x00;
5150 switch (mPrimaryDisplayOrientation) {
5151 case DisplayState::eOrientation90:
5152 flags = Transform::ROT_90;
5153 break;
5154 case DisplayState::eOrientation180:
5155 flags = Transform::ROT_180;
5156 break;
5157 case DisplayState::eOrientation270:
5158 flags = Transform::ROT_270;
5159 break;
5160 }
5161 tr.set(flags, raWidth, raHeight);
5162 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005163 }
5164
5165 // ensure that sourceCrop is inside screen
5166 if (sourceCrop.left < 0) {
5167 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5168 }
chaviwa76b2712017-09-20 12:02:26 -07005169 if (sourceCrop.right > raWidth) {
5170 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005171 }
5172 if (sourceCrop.top < 0) {
5173 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5174 }
chaviwa76b2712017-09-20 12:02:26 -07005175 if (sourceCrop.bottom > raHeight) {
5176 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005177 }
5178
Chia-I Wu36574d92018-05-16 10:54:36 -07005179 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5180 engine.setOutputDataSpace(Dataspace::SRGB);
5181 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005182
Mathias Agopian180f10d2013-04-10 22:55:41 -07005183 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005184 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005185
Iris Chang7501ed62018-04-30 14:45:42 +08005186 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5187 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5188 // convert hw orientation into flag presentation
5189 // here inverse transform needed
5190 uint8_t hw_rot_90 = 0x00;
5191 uint8_t hw_flip_hv = 0x00;
5192 switch (mPrimaryDisplayOrientation) {
5193 case DisplayState::eOrientation90:
5194 hw_rot_90 = Transform::ROT_90;
5195 hw_flip_hv = Transform::ROT_180;
5196 break;
5197 case DisplayState::eOrientation180:
5198 hw_flip_hv = Transform::ROT_180;
5199 break;
5200 case DisplayState::eOrientation270:
5201 hw_rot_90 = Transform::ROT_90;
5202 break;
5203 }
5204
5205 // transform flags operation
5206 // 1) flip H V if both have ROT_90 flag
5207 // 2) XOR these flags
5208 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5209 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5210 if (rotation_rot_90 & hw_rot_90) {
5211 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5212 }
5213 rotation = static_cast<Transform::orientation_flags>
5214 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5215 }
5216
Mathias Agopian180f10d2013-04-10 22:55:41 -07005217 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005218 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005219 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005220 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005221
chaviw50da5042018-04-09 13:49:37 -07005222 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005223 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005224 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005225
chaviwa76b2712017-09-20 12:02:26 -07005226 traverseLayers([&](Layer* layer) {
5227 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005228 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005229 if (filtering) layer->setFiltering(false);
5230 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005231}
5232
chaviwa76b2712017-09-20 12:02:26 -07005233status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5234 TraverseLayersFunction traverseLayers,
5235 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005236 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005237 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005238 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005239 ATRACE_CALL();
5240
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005241 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005242
5243 traverseLayers([&](Layer* layer) {
5244 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5245 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005246
Robert Carr03480e22018-01-04 16:02:06 -08005247 // We allow the system server to take screenshots of secure layers for
5248 // use in situations like the Screen-rotation animation and place
5249 // the impetus on WindowManager to not persist them.
5250 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005251 ALOGW("FB is protected: PERMISSION_DENIED");
5252 return PERMISSION_DENIED;
5253 }
5254
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005255 // this binds the given EGLImage as a framebuffer for the
5256 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005257 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005258 if (bufferBond.getStatus() != NO_ERROR) {
5259 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005260 return INVALID_OPERATION;
5261 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005262
Dan Stozaabcda352017-06-01 14:37:39 -07005263 // this will in fact render into our dequeued buffer
5264 // via an FBO, which means we didn't have to create
5265 // an EGLSurface and therefore we're not
5266 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005267 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005268
Dan Stozaabcda352017-06-01 14:37:39 -07005269 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005270 getRenderEngine().finish();
5271 *outSyncFd = -1;
5272
chaviwa76b2712017-09-20 12:02:26 -07005273 const auto reqWidth = renderArea.getReqWidth();
5274 const auto reqHeight = renderArea.getReqHeight();
5275
Dan Stozaabcda352017-06-01 14:37:39 -07005276 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5277 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005278 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005279 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005280 } else {
5281 base::unique_fd syncFd = getRenderEngine().flush();
5282 if (syncFd < 0) {
5283 getRenderEngine().finish();
5284 }
5285 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005286 }
5287
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005288 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005289}
5290
Mathias Agopiand5556842013-09-19 17:08:37 -07005291void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005292 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005293 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005294 for (size_t y = 0; y < h; y++) {
5295 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5296 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005297 if (p[x] != 0xFF000000) return;
5298 }
5299 }
chaviwa76b2712017-09-20 12:02:26 -07005300 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005301
Robert Carr2047fae2016-11-28 14:09:09 -08005302 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005303 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005304 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005305 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5306 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5307 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5308 static_cast<float>(state.color.a));
5309 i++;
5310 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005311 }
5312}
5313
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005314// ---------------------------------------------------------------------------
5315
Dan Stoza412903f2017-04-27 13:42:17 -07005316void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5317 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005318}
5319
Dan Stoza412903f2017-04-27 13:42:17 -07005320void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5321 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005322}
5323
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005324void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5325 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005326 const LayerVector::Visitor& visitor) {
5327 // We loop through the first level of layers without traversing,
5328 // as we need to interpret min/max layer Z in the top level Z space.
5329 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005330 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005331 continue;
5332 }
5333 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005334 // relative layers are traversed in Layer::traverseInZOrder
5335 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005336 continue;
5337 }
5338 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005339 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005340 return;
5341 }
chaviwa76b2712017-09-20 12:02:26 -07005342 if (!layer->isVisible()) {
5343 return;
5344 }
5345 visitor(layer);
5346 });
5347 }
5348}
5349
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005350}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005351
Lloyd Pique074e8122018-07-26 12:57:23 -07005352
Mathias Agopian3f844832013-08-07 21:24:32 -07005353#if defined(__gl_h_)
5354#error "don't include gl/gl.h in this file"
5355#endif
5356
5357#if defined(__gl2_h_)
5358#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005359#endif