blob: f9ea484c8d57a65851afd302d66fb070e4627b4e [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
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070041#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070042#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080043#include <compositionengine/Layer.h>
44#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080046#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070047#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080048#include <compositionengine/impl/OutputLayerCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080049#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070098#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070099#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700100#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/EventControlThread.h"
102#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700103#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
David Sodman7e4ae112018-02-09 15:02:28 -0800111#include "android-base/stringprintf.h"
112
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900113#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800114#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
115#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700116#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900117#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
chaviw1d044282017-09-27 12:19:28 -0700119#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900120#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700121
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800122namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700123
Jaesoo Lee43518572017-01-23 19:03:16 +0900124using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900125using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900126using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800127
Ady Abraham8532d012019-05-08 14:50:56 -0700128using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800129using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700130using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700131using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800132using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700133using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700134using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900135
Steven Thomasb02664d2017-07-26 18:48:28 -0700136namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700137
138#pragma clang diagnostic push
139#pragma clang diagnostic error "-Wswitch-enum"
140
141bool isWideColorMode(const ColorMode colorMode) {
142 switch (colorMode) {
143 case ColorMode::DISPLAY_P3:
144 case ColorMode::ADOBE_RGB:
145 case ColorMode::DCI_P3:
146 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700147 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700148 case ColorMode::BT2100_PQ:
149 case ColorMode::BT2100_HLG:
150 return true;
151 case ColorMode::NATIVE:
152 case ColorMode::STANDARD_BT601_625:
153 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
154 case ColorMode::STANDARD_BT601_525:
155 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
156 case ColorMode::STANDARD_BT709:
157 case ColorMode::SRGB:
158 return false;
159 }
160 return false;
161}
162
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700163bool isHdrColorMode(const ColorMode colorMode) {
164 switch (colorMode) {
165 case ColorMode::BT2100_PQ:
166 case ColorMode::BT2100_HLG:
167 return true;
168 case ColorMode::DISPLAY_P3:
169 case ColorMode::ADOBE_RGB:
170 case ColorMode::DCI_P3:
171 case ColorMode::BT2020:
172 case ColorMode::DISPLAY_BT2020:
173 case ColorMode::NATIVE:
174 case ColorMode::STANDARD_BT601_625:
175 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
176 case ColorMode::STANDARD_BT601_525:
177 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
178 case ColorMode::STANDARD_BT709:
179 case ColorMode::SRGB:
180 return false;
181 }
182 return false;
183}
184
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700185ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
186 switch (rotation) {
187 case ISurfaceComposer::eRotateNone:
188 return ui::Transform::ROT_0;
189 case ISurfaceComposer::eRotate90:
190 return ui::Transform::ROT_90;
191 case ISurfaceComposer::eRotate180:
192 return ui::Transform::ROT_180;
193 case ISurfaceComposer::eRotate270:
194 return ui::Transform::ROT_270;
195 }
196 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
197 return ui::Transform::ROT_0;
198}
199
Peiyong Linfca547f2018-07-09 13:03:33 -0700200#pragma clang diagnostic pop
201
Steven Thomasb02664d2017-07-26 18:48:28 -0700202class ConditionalLock {
203public:
204 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
205 if (lock) {
206 mMutex.lock();
207 }
208 }
209 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
210private:
211 Mutex& mMutex;
212 bool mLocked;
213};
Peiyong Linfca547f2018-07-09 13:03:33 -0700214
Peiyong Lin9d846a52018-11-05 13:18:20 -0800215// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
216bool validateCompositionDataspace(Dataspace dataspace) {
217 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
218}
219
Steven Thomasb02664d2017-07-26 18:48:28 -0700220} // namespace anonymous
221
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800222// ---------------------------------------------------------------------------
223
Mathias Agopian99b49842011-06-27 16:05:52 -0700224const String16 sHardwareTest("android.permission.HARDWARE_TEST");
225const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
226const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
227const String16 sDump("android.permission.DUMP");
228
229// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700230int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700231bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800232uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800233bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800234bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800235int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600236bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700237int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700238bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700239bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700240Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
241ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
242Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700244
Kalle Raitaa099a242017-01-11 11:17:29 -0800245std::string getHwcServiceName() {
246 char value[PROPERTY_VALUE_MAX] = {};
247 property_get("debug.sf.hwc_service_name", value, "default");
248 ALOGI("Using HWComposer service: '%s'", value);
249 return std::string(value);
250}
251
252bool useTrebleTestingOverride() {
253 char value[PROPERTY_VALUE_MAX] = {};
254 property_get("debug.sf.treble_testing_override", value, "false");
255 ALOGI("Treble testing override: '%s'", value);
256 return std::string(value) == "true";
257}
258
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800259std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
260 switch(displayColorSetting) {
261 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800263 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800265 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Enhanced");
267 default:
268 return std::string("Unknown ") +
269 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800270 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800271}
272
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
276 : mFactory(factory),
277 mPhaseOffsets(mFactory.createPhaseOffsets()),
278 mInterceptor(mFactory.createSurfaceInterceptor(this)),
279 mTimeStats(mFactory.createTimeStats()),
280 mEventQueue(mFactory.createMessageQueue()),
281 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800282
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700283SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293
Steven Thomas050b2c82017-03-06 11:45:16 -0800294 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 mDefaultCompositionDataspace =
304 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700305 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
306 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 defaultCompositionDataspace = mDefaultCompositionDataspace;
308 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
309 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
310 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
311 wideColorGamutCompositionPixelFormat =
312 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700313
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900314 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800315
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900316 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
317 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
318 switch (tmpPrimaryDisplayOrientation) {
319 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700320 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800321 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900322 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700323 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800324 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900325 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700326 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800327 break;
328 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700329 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800330 break;
331 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700332 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800333
Sundong Ahn85131bd2019-02-18 15:51:53 +0900334 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800336 // debugging stuff...
337 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700338
Mathias Agopianb4b17302013-03-20 18:36:41 -0700339 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700340 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800342 property_get("debug.sf.showupdates", value, "0");
343 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700345 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000346
347 // DDMS debugging deprecated (b/120782499)
348 property_get("debug.sf.ddms", value, "0");
349 int debugDdms = atoi(value);
350 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700351
352 property_get("debug.sf.disable_backpressure", value, "0");
353 mPropagateBackpressure = !atoi(value);
354 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700355
Ady Abraham4658e112019-07-22 13:07:26 -0700356 property_get("debug.sf.enable_gl_backpressure", value, "0");
357 mPropagateBackpressureClientComposition = atoi(value);
358 ALOGI_IF(mPropagateBackpressureClientComposition,
359 "Enabling backpressure propagation for Client Composition");
360
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800361 property_get("debug.sf.enable_hwc_vds", value, "0");
362 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800363 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800365 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800366 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700368
Yiwei Zhang243b3782018-05-15 17:40:04 -0700369 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700370 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
372
Ana Krulece5a06e02019-03-06 17:09:03 -0800373 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800374 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800375
376 int int_value = atoi(value);
377 if (int_value) {
378 mUseSmart90ForVideo = true;
379 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800380
Dan Stozaec460082018-12-17 15:35:09 -0800381 property_get("debug.sf.luma_sampling", value, "1");
382 mLumaSampling = atoi(value);
383
Ana Krulec757f63a2019-01-25 10:46:18 -0800384 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abrahamf8713e12019-06-07 18:20:51 -0700385 mVsyncModulator.setPhaseOffsets(early, gl, late,
386 mPhaseOffsets->getOffsetThresholdForNextVsync());
Dan Stoza84d619e2018-03-28 17:07:36 -0700387
Romain Guy11d63f42017-07-20 12:47:14 -0700388 // We should be reading 'persist.sys.sf.color_saturation' here
389 // but since /data may be encrypted, we need to wait until after vold
390 // comes online to attempt to read the property. The property is
391 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800392
393 if (useTrebleTestingOverride()) {
394 // Without the override SurfaceFlinger cannot connect to HIDL
395 // services that are not listed in the manifests. Considered
396 // deriving the setting from the set service name, but it
397 // would be brittle if the name that's not 'default' is used
398 // for production purposes later on.
399 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
400 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401}
402
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403void SurfaceFlinger::onFirstRef()
404{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800405 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406}
407
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700408SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409
Dan Stozac7014012014-02-14 15:03:43 -0800410void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411{
412 // the window manager died on us. prepare its eulogy.
413
Andy McFadden13a082e2012-08-24 10:16:42 -0700414 // restore initial conditions (default device unblank, etc)
415 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416
417 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700418 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419}
420
Robert Carr1db73f62016-12-21 12:58:51 -0800421static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700422 status_t err = client->initCheck();
423 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425 }
Robert Carr1db73f62016-12-21 12:58:51 -0800426 return nullptr;
427}
428
429sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
430 return initClient(new Client(this));
431}
432
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700433sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
434 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435{
436 class DisplayToken : public BBinder {
437 sp<SurfaceFlinger> flinger;
438 virtual ~DisplayToken() {
439 // no more references, this display must be terminated
440 Mutex::Autolock _l(flinger->mStateLock);
441 flinger->mCurrentState.displays.removeItem(this);
442 flinger->setTransactionFlags(eDisplayTransactionNeeded);
443 }
444 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700445 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446 : flinger(flinger) {
447 }
448 };
449
450 sp<BBinder> token = new DisplayToken(this);
451
452 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 // Display ID is assigned when virtual display is allocated by HWC.
454 DisplayDeviceState state;
455 state.isSecure = secure;
456 state.displayName = displayName;
457 mCurrentState.displays.add(token, state);
458 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 return token;
460}
461
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700462void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700463 Mutex::Autolock _l(mStateLock);
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
466 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700467 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700468 return;
469 }
470
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
472 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700473 ALOGE("destroyDisplay called for non-virtual display");
474 return;
475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 mInterceptor->saveDisplayDeletion(state.sequenceId);
477 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 setTransactionFlags(eDisplayTransactionNeeded);
479}
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
482 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800484 const auto internalDisplayId = getInternalDisplayIdLocked();
485 if (!internalDisplayId) {
486 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 }
488
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800489 std::vector<PhysicalDisplayId> displayIds;
490 displayIds.reserve(mPhysicalDisplayTokens.size());
491 displayIds.push_back(internalDisplayId->value);
492
493 for (const auto& [id, token] : mPhysicalDisplayTokens) {
494 if (id != *internalDisplayId) {
495 displayIds.push_back(id.value);
496 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499 return displayIds;
500}
501
502sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
503 Mutex::Autolock lock(mStateLock);
504 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
Ady Abraham37965d42018-11-01 13:43:32 -0700507status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
508 if (!outGetColorManagement) {
509 return BAD_VALUE;
510 }
511 *outGetColorManagement = useColorManagement;
512 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700513}
514
Lloyd Pique441d5042018-10-18 16:49:51 -0700515HWComposer& SurfaceFlinger::getHwComposer() const {
516 return mCompositionEngine->getHwComposer();
517}
518
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700519renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
520 return mCompositionEngine->getRenderEngine();
521}
522
Lloyd Pique70d91362018-10-18 16:02:55 -0700523compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
524 return *mCompositionEngine.get();
525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700529 if (mStartPropertySetThread->join() != NO_ERROR) {
530 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532 const nsecs_t now = systemTime();
533 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000534 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535
536 // wait patiently for the window manager death
537 const String16 name("window");
538 sp<IBinder> window(defaultServiceManager()->getService(name));
539 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 }
Robert Carr720e5062018-07-30 17:45:14 -0700542 sp<IBinder> input(defaultServiceManager()->getService(
543 String16("inputflinger")));
544 if (input == nullptr) {
545 ALOGE("Failed to link to input service");
546 } else {
547 mInputFlinger = interface_cast<IInputFlinger>(input);
548 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
Steven Thomas050b2c82017-03-06 11:45:16 -0800550 if (mVrFlinger) {
551 mVrFlinger->OnBootFinished();
552 }
553
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700555 // formerly we would just kill the process, but we now ask it to exit so it
556 // can choose where to stop the animation.
557 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700558
559 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
560 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
561 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700562
Ana Krulecbd6654b2019-02-15 15:18:15 -0800563 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800564 readPersistentProperties();
565 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800566
Ady Abraham97d04232019-03-05 19:48:12 -0800567 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700568 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700569 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800570
Dominik Laskowski22488f62019-03-28 09:53:04 -0700571 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800572 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800573 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800574 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800575 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800576 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800577}
578
Dan Stoza436ccf32018-06-21 12:10:12 -0700579uint32_t SurfaceFlinger::getNewTexture() {
580 {
581 std::lock_guard lock(mTexturePoolMutex);
582 if (!mTexturePool.empty()) {
583 uint32_t name = mTexturePool.back();
584 mTexturePool.pop_back();
585 ATRACE_INT("TexturePoolSize", mTexturePool.size());
586 return name;
587 }
588
589 // The pool was too small, so increase it for the future
590 ++mTexturePoolSize;
591 }
592
593 // The pool was empty, so we need to get a new texture name directly using a
594 // blocking call to the main thread
595 uint32_t name = 0;
596 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
597 return name;
598}
599
Mathias Agopian3f844832013-08-07 21:24:32 -0700600void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700601 std::lock_guard lock(mTexturePoolMutex);
602 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
603 // to actually delete this or not based on mTexturePoolSize
604 mTexturePool.push_back(texture);
605 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
613
Ana Krulec757f63a2019-01-25 10:46:18 -0800614 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800618 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700619 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
620 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800621 auto resyncCallback =
622 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800623
Ana Krulecc2870422019-01-29 19:00:58 -0800624 mAppConnectionHandle =
Ady Abrahamf8713e12019-06-07 18:20:51 -0700625 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
626 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800627 resyncCallback,
628 impl::EventThread::InterceptVSyncsCallback());
Ady Abrahamf8713e12019-06-07 18:20:51 -0700629 mSfConnectionHandle =
630 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
631 mPhaseOffsets->getOffsetThresholdForNextVsync(),
632 resyncCallback, [this](nsecs_t timestamp) {
633 mInterceptor->saveVSyncEvent(timestamp);
634 });
Ana Krulecc2870422019-01-29 19:00:58 -0800635
636 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
637 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
638 mSfConnectionHandle.get());
639
Kevin DuBois413287f2019-02-25 08:46:47 -0800640 mRegionSamplingThread =
641 new RegionSamplingThread(*this, *mScheduler,
642 RegionSamplingThread::EnvironmentTimingTunables());
643
Steven Thomasb02664d2017-07-26 18:48:28 -0700644 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700645 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700646 renderEngineFeature |= (useColorManagement ?
647 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700648 renderEngineFeature |= (useContextPriority ?
649 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700650 renderEngineFeature |=
651 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
652 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700653
654 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800655 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700656 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700657 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800658 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700659
660 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
661 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700662 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
663 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800664 // Process any initial hotplug and resulting display changes.
665 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 const auto display = getDefaultDisplayDeviceLocked();
667 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700668 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700669 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800670
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700672 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700673 // This callback is called from the vr flinger dispatch thread. We
674 // need to call signalTransaction(), which requires holding
675 // mStateLock when we're not on the main thread. Acquiring
676 // mStateLock from the vr flinger dispatch thread might trigger a
677 // deadlock in surface flinger (see b/66916578), so post a message
678 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700679 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700680 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
681 mVrFlingerRequestsDisplay = requestDisplay;
682 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700683 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800684 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
686 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700687 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700688 .value_or(0),
689 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (!mVrFlinger) {
691 ALOGE("Failed to start vrflinger");
692 }
693 }
694
Mathias Agopian92a979a2012-08-02 18:32:23 -0700695 // initialize our drawing state
696 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700697
Andy McFadden13a082e2012-08-24 10:16:42 -0700698 // set initial conditions (e.g. unblank default device)
699 initializeDisplays();
700
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700701 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700702
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700704
705 const bool presentFenceReliable =
706 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
707 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708
709 if (mStartPropertySetThread->Start() != NO_ERROR) {
710 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800711 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712
Alec Mouri93bc83d2019-04-17 14:47:43 -0700713 mScheduler->setChangeRefreshRateCallback(
714 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
715 Mutex::Autolock lock(mStateLock);
716 setRefreshRateTo(type, event);
717 });
Alec Mouri53b5d032019-07-11 13:56:22 -0700718 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
719 Mutex::Autolock lock(mStateLock);
720 const auto display = getDefaultDisplayDeviceLocked();
721 if (!display) {
722 // If we don't have a default display the fallback to the default
723 // refresh rate type
724 return RefreshRateType::DEFAULT;
725 }
726
727 const int configId = display->getActiveConfig();
728 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
729 if (refresh && refresh->configId == configId) {
730 return type;
731 }
732 }
733 // This should never happen, but just gracefully fallback to default.
734 return RefreshRateType::DEFAULT;
735 });
Alec Mouridc28b372019-04-18 21:17:13 -0700736 mScheduler->setGetVsyncPeriodCallback([this] {
737 Mutex::Autolock lock(mStateLock);
738 return getVsyncPeriod();
739 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700740
Dominik Laskowski22488f62019-03-28 09:53:04 -0700741 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
742 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700745}
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 Mutex::Autolock _l(mStateLock);
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750 char value[PROPERTY_VALUE_MAX];
751
752 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700754 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100756
757 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700758 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800759
760 property_get("persist.sys.sf.color_mode", value, "0");
761 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700762}
763
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Start boot animation service by setting a property mailbox
766 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800768 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 if (mStartPropertySetThread->join() != NO_ERROR) {
770 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700779 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800783
Jamie Gennis582270d2011-08-17 18:19:00 -0700784bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800786 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800787 return authenticateSurfaceTextureLocked(bufferProducer);
788}
789
790bool SurfaceFlinger::authenticateSurfaceTextureLocked(
791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800792 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800793 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800794}
795
Brian Anderson6b376712017-04-04 10:51:39 -0700796status_t SurfaceFlinger::getSupportedFrameTimestamps(
797 std::vector<FrameEvent>* outSupported) const {
798 *outSupported = {
799 FrameEvent::REQUESTED_PRESENT,
800 FrameEvent::ACQUIRE,
801 FrameEvent::LATCH,
802 FrameEvent::FIRST_REFRESH_START,
803 FrameEvent::LAST_REFRESH_START,
804 FrameEvent::GPU_COMPOSITION_DONE,
805 FrameEvent::DEQUEUE_READY,
806 FrameEvent::RELEASE,
807 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 ConditionalLock _l(mStateLock,
809 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700810 if (!getHwComposer().hasCapability(
811 HWC2::Capability::PresentFenceIsNotReliable)) {
812 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
813 }
814 return NO_ERROR;
815}
816
Dominik Laskowski22488f62019-03-28 09:53:04 -0700817status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
818 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700819 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 return BAD_VALUE;
821 }
822
Dominik Laskowski22488f62019-03-28 09:53:04 -0700823 Mutex::Autolock lock(mStateLock);
824
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800825 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700826 if (!displayId) {
827 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700828 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 // TODO: Not sure if display density should handled by SF any longer
831 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700834 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800835 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700836 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 }
838 return density;
839 }
840 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 return getDensityFromProperty("ro.sf.lcd_density"); }
845 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dominik Laskowski075d3172018-05-24 15:50:06 -0700849 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 DisplayInfo info = DisplayInfo();
851
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 float xdpi = hwConfig->getDpiX();
853 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700854
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700855 info.w = hwConfig->getWidth();
856 info.h = hwConfig->getHeight();
857 // Default display viewport to display width and height
858 info.viewportW = info.w;
859 info.viewportH = info.h;
860
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800861 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 // The density of the device is provided by a build property
863 float density = Density::getBuildDensity() / 160.0f;
864 if (density == 0) {
865 // the build doesn't provide a density -- this is wrong!
866 // use xdpi instead
867 ALOGE("ro.sf.lcd_density must be defined as a build property");
868 density = xdpi / 160.0f;
869 }
870 if (Density::getEmuDensity()) {
871 // if "qemu.sf.lcd_density" is specified, it overrides everything
872 xdpi = ydpi = density = Density::getEmuDensity();
873 density /= 160.0f;
874 }
875 info.density = density;
876
877 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700878 const auto display = getDefaultDisplayDeviceLocked();
879 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700880
881 // This is for screenrecord
882 const Rect viewport = display->getViewport();
883 if (viewport.isValid()) {
884 info.viewportW = uint32_t(viewport.getWidth());
885 info.viewportH = uint32_t(viewport.getHeight());
886 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 } else {
888 // TODO: where should this value come from?
889 static const int TV_DENSITY = 213;
890 info.density = TV_DENSITY / 160.0f;
891 info.orientation = 0;
892 }
893
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 info.xdpi = xdpi;
895 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700897 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
898 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
899 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800900
Andy McFadden91b2ca82014-06-13 14:04:23 -0700901 // This is how far in advance a buffer must be queued for
902 // presentation at a given time. If you want a buffer to appear
903 // on the screen at time N, you must submit the buffer before
904 // (N - presentationDeadline).
905 //
906 // Normally it's one full refresh period (to give SF a chance to
907 // latch the buffer), but this can be reduced by configuring a
908 // DispSync offset. Any additional delays introduced by the hardware
909 // composer or panel must be accounted for here.
910 //
911 // We add an additional 1ms to allow for processing time and
912 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700913 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700914
915 // All non-virtual displays are currently considered secure.
916 info.secure = true;
917
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800918 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700919 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800920 std::swap(info.w, info.h);
921 }
922
Michael Wright28f24d02016-07-12 13:30:53 -0700923 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700924 }
925
Dan Stoza7f7da322014-05-02 15:26:25 -0700926 return NO_ERROR;
927}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
930 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700931 return BAD_VALUE;
932 }
933
Ana Krulecc2870422019-01-29 19:00:58 -0800934 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700935 return NO_ERROR;
936}
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
939 const auto display = getDisplayDevice(displayToken);
940 if (!display) {
941 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800942 return BAD_VALUE;
943 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700946}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700947
Ady Abraham03b02dd2019-03-21 15:40:11 -0700948void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800952 // config twice. However event generation config might have changed so we need to update it
953 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800954 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700955 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
956 mDesiredActiveConfig = info;
957 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958
959 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800960 // This will trigger HWC refresh without resetting the idle timer.
961 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700962 // Start receiving vsync samples now, so that we can detect a period
963 // switch.
964 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham7849f2a2019-05-28 18:07:44 -0700965 // As we called to set period, we will call to onRefreshRateChangeCompleted once
966 // DispSync model is locked.
967 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700968 mPhaseOffsets->setRefreshRateType(info.type);
969 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abrahamf8713e12019-06-07 18:20:51 -0700970 mVsyncModulator.setPhaseOffsets(early, gl, late,
971 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 mDesiredActiveConfigChanged = true;
974 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700975
976 if (mRefreshRateOverlay) {
977 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979}
980
981status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
982 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800983
984 std::vector<int32_t> allowedConfig;
985 allowedConfig.push_back(mode);
986
987 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988}
989
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990void SurfaceFlinger::setActiveConfigInternal() {
991 ATRACE_CALL();
992
Dominik Laskowski22488f62019-03-28 09:53:04 -0700993 const auto display = getDefaultDisplayDeviceLocked();
994 if (!display) {
995 return;
996 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997
Dominik Laskowski22488f62019-03-28 09:53:04 -0700998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
999 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
1000
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001001 display->setActiveConfig(mUpcomingActiveConfig.configId);
1002
Alec Mouri754c98a2019-03-18 18:53:42 -07001003 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001004 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abrahamf8713e12019-06-07 18:20:51 -07001005 mVsyncModulator.setPhaseOffsets(early, gl, late,
1006 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001007 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001008
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001009 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001010 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1011 mUpcomingActiveConfig.configId);
1012 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013}
1014
Ady Abraham7849f2a2019-05-28 18:07:44 -07001015void SurfaceFlinger::desiredActiveConfigChangeDone() {
1016 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1017 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1018 mDesiredActiveConfigChanged = false;
1019 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1020
1021 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1022 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
1023 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abrahamf8713e12019-06-07 18:20:51 -07001024 mVsyncModulator.setPhaseOffsets(early, gl, late,
1025 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham7849f2a2019-05-28 18:07:44 -07001026}
1027
Dominik Laskowski22488f62019-03-28 09:53:04 -07001028bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001029 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001031 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001033 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 return true;
1035 }
1036
1037 // We received the present fence from the HWC, so we assume it successfully updated
1038 // the config, hence we update SF.
1039 mCheckPendingFence = false;
1040 setActiveConfigInternal();
1041 }
1042
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001043 // Store the local variable to release the lock.
1044 ActiveConfigInfo desiredActiveConfig;
1045 {
1046 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001047 if (!mDesiredActiveConfigChanged) {
1048 return false;
1049 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001050 desiredActiveConfig = mDesiredActiveConfig;
1051 }
1052
Dominik Laskowski22488f62019-03-28 09:53:04 -07001053 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1055 // display is not valid or we are already in the requested mode
1056 // on both cases there is nothing left to do
Ady Abraham7849f2a2019-05-28 18:07:44 -07001057 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001059 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001060
Ady Abraham838de062019-02-04 10:24:03 -08001061 // Desired active config was set, it is different than the config currently in use, however
1062 // allowed configs might have change by the time we process the refresh.
1063 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001064 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham7849f2a2019-05-28 18:07:44 -07001065 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001066 return false;
1067 }
Alec Mouri53b5d032019-07-11 13:56:22 -07001068
Ady Abrahamb838aed2019-02-12 15:30:16 -08001069 mUpcomingActiveConfig = desiredActiveConfig;
1070 const auto displayId = display->getId();
1071 LOG_ALWAYS_FATAL_IF(!displayId);
1072
1073 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1074 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1075
1076 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001078 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001079 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001080}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1083 Vector<ColorMode>* outColorModes) {
1084 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001085 return BAD_VALUE;
1086 }
1087
Peiyong Lina52f0292018-03-14 17:26:31 -07001088 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001089 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001090 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001091 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1092
1093 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1094 if (!displayId) {
1095 return NAME_NOT_FOUND;
1096 }
1097
Dominik Laskowski075d3172018-05-24 15:50:06 -07001098 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001099 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001100 }
Michael Wright28f24d02016-07-12 13:30:53 -07001101 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001102
1103 // If it's built-in display and the configuration claims it's not wide color capable,
1104 // filter out all wide color modes. The typical reason why this happens is that the
1105 // hardware is not good enough to support GPU composition of wide color, and thus the
1106 // OEMs choose to disable this capability.
1107 if (isInternalDisplay && !hasWideColorDisplay) {
1108 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1109 isWideColorMode);
1110 } else {
1111 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1112 }
Michael Wright28f24d02016-07-12 13:30:53 -07001113
1114 return NO_ERROR;
1115}
1116
Daniel Solomon42d04562019-01-20 21:03:19 -08001117status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1118 ui::DisplayPrimaries &primaries) {
1119 if (!displayToken) {
1120 return BAD_VALUE;
1121 }
1122
1123 // Currently we only support this API for a single internal display.
1124 if (getInternalDisplayToken() != displayToken) {
1125 return BAD_VALUE;
1126 }
1127
1128 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1129 return NO_ERROR;
1130}
1131
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001132ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1133 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001134 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001135 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001136 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001137}
1138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001140 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001141 Vector<ColorMode> modes;
1142 getDisplayColorModes(displayToken, &modes);
1143 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1144 if (mode < ColorMode::NATIVE || !exists) {
1145 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1146 decodeColorMode(mode).c_str(), mode, displayToken.get());
1147 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001148 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001149 const auto display = getDisplayDevice(displayToken);
1150 if (!display) {
1151 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1152 decodeColorMode(mode).c_str(), mode, displayToken.get());
1153 } else if (display->isVirtual()) {
1154 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1155 decodeColorMode(mode).c_str(), mode);
1156 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001157 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1158 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 }
1160 }));
1161
Michael Wright28f24d02016-07-12 13:30:53 -07001162 return NO_ERROR;
1163}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001164
Svetoslavd85084b2014-03-20 10:28:31 -07001165status_t SurfaceFlinger::clearAnimationFrameStats() {
1166 Mutex::Autolock _l(mStateLock);
1167 mAnimFrameTracker.clearStats();
1168 return NO_ERROR;
1169}
1170
1171status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1172 Mutex::Autolock _l(mStateLock);
1173 mAnimFrameTracker.getStats(outStats);
1174 return NO_ERROR;
1175}
1176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001177status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1178 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001179 Mutex::Autolock _l(mStateLock);
1180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001181 const auto display = getDisplayDeviceLocked(displayToken);
1182 if (!display) {
1183 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001184 return BAD_VALUE;
1185 }
1186
Peiyong Linfb069302018-04-25 14:34:31 -07001187 // At this point the DisplayDeivce should already be set up,
1188 // meaning the luminance information is already queried from
1189 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001190 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001191 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1192 capabilities.getDesiredMaxLuminance(),
1193 capabilities.getDesiredMaxAverageLuminance(),
1194 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001195
1196 return NO_ERROR;
1197}
1198
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001199status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1200 ui::PixelFormat* outFormat,
1201 ui::Dataspace* outDataspace,
1202 uint8_t* outComponentMask) const {
1203 if (!outFormat || !outDataspace || !outComponentMask) {
1204 return BAD_VALUE;
1205 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001206 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001207 if (!display || !display->getId()) {
1208 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1209 return BAD_VALUE;
1210 }
1211 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1212 outDataspace, outComponentMask);
1213}
1214
Kevin DuBois74e53772018-11-19 10:52:38 -08001215status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1216 bool enable, uint8_t componentMask,
1217 uint64_t maxFrames) const {
1218 const auto display = getDisplayDevice(displayToken);
1219 if (!display || !display->getId()) {
1220 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1221 return BAD_VALUE;
1222 }
1223
1224 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1225 componentMask, maxFrames);
1226}
1227
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001228status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1229 uint64_t maxFrames, uint64_t timestamp,
1230 DisplayedFrameStats* outStats) const {
1231 const auto display = getDisplayDevice(displayToken);
1232 if (!display || !display->getId()) {
1233 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1234 return BAD_VALUE;
1235 }
1236
1237 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1238 outStats);
1239}
1240
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001241status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1242 if (!outSupported) {
1243 return BAD_VALUE;
1244 }
1245 *outSupported = getRenderEngine().supportsProtectedContent();
1246 return NO_ERROR;
1247}
1248
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001249status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1250 bool* outIsWideColorDisplay) const {
1251 if (!displayToken || !outIsWideColorDisplay) {
1252 return BAD_VALUE;
1253 }
1254 Mutex::Autolock _l(mStateLock);
1255 const auto display = getDisplayDeviceLocked(displayToken);
1256 if (!display) {
1257 return BAD_VALUE;
1258 }
Peiyong Linff84a152019-05-17 18:36:19 -07001259
1260 // Use hasWideColorDisplay to override built-in display.
1261 const auto displayId = display->getId();
1262 if (displayId && displayId == getInternalDisplayIdLocked()) {
1263 *outIsWideColorDisplay = hasWideColorDisplay;
1264 return NO_ERROR;
1265 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001266 *outIsWideColorDisplay = display->hasWideColorGamut();
1267 return NO_ERROR;
1268}
1269
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001270status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001271 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001273
Chia-I Wu90f669f2017-10-05 14:24:41 -07001274 if (mInjectVSyncs == enable) {
1275 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001276 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001277
Ana Krulecc2870422019-01-29 19:00:58 -08001278 auto resyncCallback =
1279 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001280
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001281 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001282 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001283 if (enable) {
1284 ALOGV("VSync Injections enabled");
1285 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001286 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001287 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001288 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001289 impl::EventThread::InterceptVSyncsCallback(),
1290 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001291 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001292 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001293 } else {
1294 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001295 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1296 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001297 }
1298
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001299 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001300 }));
1301
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001302 return NO_ERROR;
1303}
1304
1305status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001306 Mutex::Autolock _l(mStateLock);
1307
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001308 if (!mInjectVSyncs) {
1309 ALOGE("VSync Injections not enabled");
1310 return BAD_VALUE;
1311 }
1312 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1313 ALOGV("Injecting VSync inside SurfaceFlinger");
1314 mVSyncInjector->onInjectSyncEvent(when);
1315 }
1316 return NO_ERROR;
1317}
1318
Lloyd Pique755e3192018-01-31 16:46:15 -08001319status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1320 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001321 // Try to acquire a lock for 1s, fail gracefully
1322 const status_t err = mStateLock.timedLock(s2ns(1));
1323 const bool locked = (err == NO_ERROR);
1324 if (!locked) {
1325 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1326 return TIMED_OUT;
1327 }
1328
1329 outLayers->clear();
1330 mCurrentState.traverseInZOrder([&](Layer* layer) {
1331 outLayers->push_back(layer->getLayerDebugInfo());
1332 });
1333
1334 mStateLock.unlock();
1335 return NO_ERROR;
1336}
1337
Peiyong Linc6780972018-10-28 15:24:08 -07001338status_t SurfaceFlinger::getCompositionPreference(
1339 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1340 Dataspace* outWideColorGamutDataspace,
1341 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001342 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001343 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001344 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001345 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001346 return NO_ERROR;
1347}
1348
Dan Stozaec460082018-12-17 15:35:09 -08001349status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1350 const sp<IBinder>& stopLayerHandle,
1351 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001352 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001353 return BAD_VALUE;
1354 }
1355 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001356 return NO_ERROR;
1357}
1358
Dan Stozaec460082018-12-17 15:35:09 -08001359status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001360 if (!listener) {
1361 return BAD_VALUE;
1362 }
Dan Stozaec460082018-12-17 15:35:09 -08001363 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001364 return NO_ERROR;
1365}
Dan Gittik57e63c52019-01-18 16:37:54 +00001366
1367status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1368 bool* outSupport) const {
1369 if (!displayToken || !outSupport) {
1370 return BAD_VALUE;
1371 }
1372 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1373 if (!displayId) {
1374 return NAME_NOT_FOUND;
1375 }
1376 *outSupport =
1377 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1378 return NO_ERROR;
1379}
1380
1381status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1382 float brightness) const {
1383 if (!displayToken) {
1384 return BAD_VALUE;
1385 }
1386 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1387 if (!displayId) {
1388 return NAME_NOT_FOUND;
1389 }
1390 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1391}
1392
Ady Abraham8532d012019-05-08 14:50:56 -07001393status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1394 PowerHint powerHint = static_cast<PowerHint>(hintId);
1395
1396 if (powerHint == PowerHint::INTERACTION) {
1397 mScheduler->notifyTouchEvent();
1398 }
1399
1400 return NO_ERROR;
1401}
1402
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001403// ----------------------------------------------------------------------------
1404
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001405sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham9b586692019-06-04 16:04:04 -07001406 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001407 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001408 Mutex::Autolock lock(mStateLock);
1409 return getVsyncPeriod();
1410 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001411
Ana Krulecc2870422019-01-29 19:00:58 -08001412 const auto& handle =
1413 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001414
Ady Abraham9b586692019-06-04 16:04:04 -07001415 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1416 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001417}
1418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001419// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001420
1421void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001422 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423}
1424
1425void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001426 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001427 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001428}
1429
1430void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001431 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001432 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001433}
1434
1435void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001436 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001437 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001438}
1439
1440status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001441 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001442 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001443}
1444
1445status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001446 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001447 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001448 if (res == NO_ERROR) {
1449 msg->wait();
1450 }
1451 return res;
1452}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001453
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001454void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001455 do {
1456 waitForEvent();
1457 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458}
1459
Dominik Laskowski83b88212018-12-11 13:34:06 -08001460nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001461 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001462 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1463 return 0;
1464 }
1465
1466 const auto config = getHwComposer().getActiveConfig(*displayId);
1467 return config ? config->getVsyncPeriod() : 0;
1468}
1469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1471 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001472 ATRACE_NAME("SF onVsync");
1473
Steven Thomas3cfac282017-02-06 12:29:30 -08001474 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001476 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 return;
1478 }
1479
Dominik Laskowski075d3172018-05-24 15:50:06 -07001480 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001481 return;
1482 }
1483
Dominik Laskowski075d3172018-05-24 15:50:06 -07001484 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001485 // For now, we don't do anything with external display vsyncs.
1486 return;
1487 }
1488
Alec Mouri5b3f19b2019-05-20 18:32:22 -07001489 bool periodFlushed = false;
1490 mScheduler->addResyncSample(timestamp, &periodFlushed);
1491 if (periodFlushed) {
1492 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001493 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001494}
1495
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001496void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001497 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1498 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499}
1500
Dominik Laskowski22488f62019-03-28 09:53:04 -07001501bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1502 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001503}
1504
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001505void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001506 const auto display = getDefaultDisplayDeviceLocked();
1507 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001508 return;
1509 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001510 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001511
Ana Krulec7d1d6832018-12-27 11:10:09 -08001512 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001513 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001514 if (!refreshRateConfig) {
1515 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001516 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001517 }
Ady Abraham1902d072019-03-01 17:18:59 -08001518
Alec Mouri0a1cc962019-03-14 12:33:02 -07001519 const int desiredConfigId = refreshRateConfig->configId;
1520
Dominik Laskowski22488f62019-03-28 09:53:04 -07001521 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001522 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1523 return;
1524 }
1525
Dominik Laskowski22488f62019-03-28 09:53:04 -07001526 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001527}
1528
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001529void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001530 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001531 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001532 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001533
Lloyd Piqueba04e622017-12-14 17:11:26 -08001534 // Ignore events that do not have the right sequenceId.
1535 if (sequenceId != getBE().mComposerSequenceId) {
1536 return;
1537 }
1538
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 // Only lock if we're not on the main thread. This function is normally
1540 // called on a hwbinder thread, but for the primary display it's called on
1541 // the main thread with the state lock already held, so don't attempt to
1542 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001543 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001544
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001545 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001546
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001547 if (std::this_thread::get_id() == mMainThreadId) {
1548 // Process all pending hot plug events immediately if we are on the main thread.
1549 processDisplayHotplugEventsLocked();
1550 }
1551
Lloyd Piqueba04e622017-12-14 17:11:26 -08001552 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001553}
1554
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001555void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001556 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001557 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001559 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001560 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001561}
1562
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001563void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001564 ATRACE_CALL();
Ady Abraham48630142019-06-03 17:10:55 -07001565
1566 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1567 // display power state.
1568 postMessageAsync(new LambdaMessage(
1569 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1570}
1571
1572void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1573 ATRACE_CALL();
1574
Ady Abrahamb0006972019-06-11 10:52:26 -07001575 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1576
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001577 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham48630142019-06-03 17:10:55 -07001578 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1579 if (display && display->isPoweredOn()) {
Ady Abrahamb0006972019-06-11 10:52:26 -07001580 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham48630142019-06-03 17:10:55 -07001581 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001582 }
Mathias Agopian86303202012-07-24 22:46:10 -07001583}
1584
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001585// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001586void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001587 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001588 // Clear the drawing state so that the logic inside of
1589 // handleTransactionLocked will fire. It will determine the delta between
1590 // mCurrentState and mDrawingState and re-apply all changes when we make the
1591 // transition.
1592 mDrawingState.displays.clear();
1593 mDisplays.clear();
1594}
1595
Steven Thomas050b2c82017-03-06 11:45:16 -08001596void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001597 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001598 if (!mVrFlinger)
1599 return;
1600 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001601 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001602 return;
1603 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001604
Lloyd Pique441d5042018-10-18 16:49:51 -07001605 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 ALOGE("Vr flinger is only supported for remote hardware composer"
1607 " service connections. Ignoring request to transition to vr"
1608 " flinger.");
1609 mVrFlingerRequestsDisplay = false;
1610 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001611 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001612
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001613 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001614
Steven Thomas0123ac62018-07-12 11:32:34 -07001615 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001616 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001617
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001618 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001619
1620 // Clear out all the output layers from the composition engine for all
1621 // displays before destroying the hardware composer interface. This ensures
1622 // any HWC layers are destroyed through that interface before it becomes
1623 // invalid.
1624 for (const auto& [token, displayDevice] : mDisplays) {
1625 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1626 compositionengine::Output::OutputLayers());
1627 }
1628
Steven Thomas0123ac62018-07-12 11:32:34 -07001629 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1630 // called below. Clear the reference now so we don't accidentally use it
1631 // later.
1632 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001633
Steven Thomasb02664d2017-07-26 18:48:28 -07001634 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001635 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001636 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001637
Steven Thomasb02664d2017-07-26 18:48:28 -07001638 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001639 // Delete the current instance before creating the new one
1640 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1641 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1642 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1643 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001644
Lloyd Pique441d5042018-10-18 16:49:51 -07001645 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001646 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001647
1648 if (vrFlingerRequestsDisplay) {
1649 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651
1652 mVisibleRegionsDirty = true;
1653 invalidateHwcGeometry();
1654
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001655 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001656 display = getDefaultDisplayDeviceLocked();
1657 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001658 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001659
Steven Thomasb02664d2017-07-26 18:48:28 -07001660 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001661 const nsecs_t vsyncPeriod = getVsyncPeriod();
1662 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001663
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001664 // The present fences returned from vr_hwc are not an accurate
1665 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001666 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001667
Steven Thomasb02664d2017-07-26 18:48:28 -07001668 // Use phase of 0 since phase is not known.
1669 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001670 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001671 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001672
Ana Krulecc2870422019-01-29 19:00:58 -08001673 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001674
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001675 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001676 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001677}
1678
Ady Abrahambe0f9482019-04-24 15:41:53 -07001679bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1680 // We are storing the last 2 present fences. If sf's phase offset is to be
1681 // woken up before the actual vsync but targeting the next vsync, we need to check
1682 // fence N-2
1683 const sp<Fence>& fence =
1684 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1685 ? mPreviousPresentFences[0]
1686 : mPreviousPresentFences[1];
1687
1688 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1689}
1690
Alec Mouri746654a2019-06-06 13:28:34 -07001691nsecs_t SurfaceFlinger::getExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
1692 DisplayStatInfo stats;
1693 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham83127b72019-06-12 17:11:12 -07001694 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouri746654a2019-06-06 13:28:34 -07001695 // Inflate the expected present time if we're targetting the next vsync.
1696 const nsecs_t correctedTime =
1697 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1698 ? presentTime
1699 : presentTime + stats.vsyncPeriod;
1700 return correctedTime;
1701}
1702
Dominik Laskowski22488f62019-03-28 09:53:04 -07001703void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001704 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001705 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001706 case MessageQueue::INVALIDATE: {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001707 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001708 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1709 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1710 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1711 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1712 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1713 if (frameMissed) {
1714 mFrameMissedCount++;
1715 mTimeStats->incrementMissedFrames();
1716 }
1717
Alec Mouri40189b02019-03-05 15:07:54 -08001718 if (hwcFrameMissed) {
1719 mHwcFrameMissedCount++;
1720 }
1721
1722 if (gpuFrameMissed) {
1723 mGpuFrameMissedCount++;
1724 }
1725
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001726 if (mUseSmart90ForVideo) {
1727 // This call is made each time SF wakes up and creates a new frame. It is part
1728 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001729 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001730 }
1731
Ady Abrahamb838aed2019-02-12 15:30:16 -08001732 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001733 break;
1734 }
1735
Ady Abraham4658e112019-07-22 13:07:26 -07001736 if (frameMissed && mPropagateBackpressure) {
1737 if ((hwcFrameMissed && !gpuFrameMissed) ||
1738 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001739 signalLayerUpdate();
1740 break;
1741 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001742 }
Dan Stoza50182882016-07-08 12:02:20 -07001743
Steven Thomas050b2c82017-03-06 11:45:16 -08001744 // Now that we're going to make it to the handleMessageTransaction()
1745 // call below it's safe to call updateVrFlinger(), which will
1746 // potentially trigger a display handoff.
1747 updateVrFlinger();
1748
Dan Stoza6b9454d2014-11-07 16:00:59 -08001749 bool refreshNeeded = handleMessageTransaction();
1750 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001751
1752 updateCursorAsync();
1753 updateInputFlinger();
1754
Dan Stoza58784442014-12-02 16:58:17 -08001755 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001756 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001757 // Signal a refresh if a transaction modified the window state,
1758 // a new buffer was latched, or if HWC has requested a full
1759 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001760 signalRefresh();
1761 }
1762 break;
1763 }
1764 case MessageQueue::REFRESH: {
1765 handleMessageRefresh();
1766 break;
1767 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001768 }
1769}
1770
Dan Stoza6b9454d2014-11-07 16:00:59 -08001771bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001772 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001773 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001774
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001775 bool flushedATransaction = flushTransactionQueues();
1776
1777 bool runHandleTransaction = transactionFlags &&
1778 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1779
1780 if (runHandleTransaction) {
1781 handleTransaction(eTransactionMask);
1782 } else {
1783 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001784 }
1785
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001786 if (transactionFlushNeeded()) {
1787 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001788 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001789
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001790 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001791}
1792
Mathias Agopian4fec8732012-06-29 14:12:52 -07001793void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001794 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001795
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001796 mRefreshPending = false;
1797
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001798 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001799 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001800 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001801 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001802 for (const auto& [token, display] : mDisplays) {
1803 beginFrame(display);
1804 prepareFrame(display);
1805 doDebugFlashRegions(display, repaintEverything);
1806 doComposition(display, repaintEverything);
1807 }
1808
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001809 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001810
1811 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001812 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001813
Dan Stozabfbffeb2016-07-21 14:49:33 -07001814 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001815 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001816 for (const auto& [token, displayDevice] : mDisplays) {
1817 auto display = displayDevice->getCompositionDisplay();
1818 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001819 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001821 mHadDeviceComposition =
1822 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001823 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001824
Jorim Jaggi90535212018-05-23 23:44:06 +02001825 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001826
David Sodman7e4ae112018-02-09 15:02:28 -08001827 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001828}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001829
David Sodmanfa9b2af2017-12-24 13:28:59 -08001830
1831bool SurfaceFlinger::handleMessageInvalidate() {
1832 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001833 bool refreshNeeded = handlePageFlip();
1834
Vishnu Nair4351ad52019-02-11 14:13:02 -08001835 if (mVisibleRegionsDirty) {
1836 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001837 if (mTracingEnabled) {
1838 mTracing.notify("visibleRegionsDirty");
1839 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001840 }
1841
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001842 for (auto& layer : mLayersPendingRefresh) {
1843 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001844 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001845 invalidateLayerStack(layer, visibleReg);
1846 }
1847 mLayersPendingRefresh.clear();
1848 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001849}
1850
David Sodman79bba0e2018-08-05 18:07:49 -07001851void SurfaceFlinger::calculateWorkingSet() {
1852 ATRACE_CALL();
1853 ALOGV(__FUNCTION__);
1854
David Sodman79bba0e2018-08-05 18:07:49 -07001855 // build the h/w work list
1856 if (CC_UNLIKELY(mGeometryInvalid)) {
1857 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001858 for (const auto& [token, displayDevice] : mDisplays) {
1859 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001860
Lloyd Piquea83776c2019-01-29 18:42:32 -08001861 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001862
Lloyd Piquea83776c2019-01-29 18:42:32 -08001863 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1864 auto& compositionState = layer->editState();
1865 compositionState.forceClientComposition = false;
1866 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1867 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001868 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001869
Lloyd Piquea83776c2019-01-29 18:42:32 -08001870 // The output Z order is set here based on a simple counter.
1871 compositionState.z = zOrder++;
1872
1873 // Update the display independent composition state. This goes
1874 // to the general composition layer state structure.
1875 // TODO: Do this once per compositionengine::CompositionLayer.
1876 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1877 true);
1878
1879 // Recalculate the geometry state of the output layer.
1880 layer->updateCompositionState(true);
1881
1882 // Write the updated geometry state to the HWC
1883 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001884 }
1885 }
1886 }
1887
1888 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001889 for (const auto& [token, displayDevice] : mDisplays) {
1890 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001891 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001892 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001893 continue;
1894 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001895 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001896
1897 if (mDrawingState.colorMatrixChanged) {
1898 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001899 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001900 Dataspace targetDataspace = Dataspace::UNKNOWN;
1901 if (useColorManagement) {
1902 ColorMode colorMode;
1903 RenderIntent renderIntent;
1904 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1905 display->setColorMode(colorMode, targetDataspace, renderIntent);
1906 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07001907 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001908 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001909 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001910 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1911 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001912 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001913 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001914 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1915 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001916 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001917 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001918 }
1919
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001920 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001921 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001922 }
1923
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001924 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001925 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001926 layer->setCompositionType(displayDevice,
1927 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001928 continue;
1929 }
1930
Lloyd Pique32cbe282018-10-19 13:09:22 -07001931 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001932 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Peiyong Lin34ea5b92019-03-15 18:40:15 -07001933 displayDevice->getSupportedPerFrameMetadata(),
1934 isHdrColorMode(displayState.colorMode) ? Dataspace::UNKNOWN
1935 : targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001936 }
1937 }
1938
1939 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001940
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001941 for (const auto& [token, displayDevice] : mDisplays) {
1942 auto display = displayDevice->getCompositionDisplay();
1943 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001944 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1945 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1946 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001947 }
1948 }
David Sodman79bba0e2018-08-05 18:07:49 -07001949}
1950
Lloyd Pique32cbe282018-10-19 13:09:22 -07001951void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1952 bool repaintEverything) {
1953 auto display = displayDevice->getCompositionDisplay();
1954 const auto& displayState = display->getState();
1955
Mathias Agopiancd60f992012-08-16 16:28:27 -07001956 // is debugging enabled
1957 if (CC_LIKELY(!mDebugRegion))
1958 return;
1959
Lloyd Pique32cbe282018-10-19 13:09:22 -07001960 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001961 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001962 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001963 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001964 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001965 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001966 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001967
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001968 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001969 }
1970 }
1971
Lloyd Pique32cbe282018-10-19 13:09:22 -07001972 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001973
1974 if (mDebugRegion > 1) {
1975 usleep(mDebugRegion * 1000);
1976 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001977
Lloyd Pique32cbe282018-10-19 13:09:22 -07001978 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001979}
1980
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001981void SurfaceFlinger::logLayerStats() {
1982 ATRACE_CALL();
1983 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001984 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001985 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001986 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001987 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001988 }
1989 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001990
1991 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001992 }
1993}
1994
David Sodman2b406362017-12-15 13:33:47 -08001995void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001996{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001997 ATRACE_CALL();
1998 ALOGV("preComposition");
1999
David Sodman2b406362017-12-15 13:33:47 -08002000 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2001
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002003 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002004 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005 needExtraInvalidate = true;
2006 }
Robert Carr2047fae2016-11-28 14:09:09 -08002007 });
2008
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009 if (needExtraInvalidate) {
2010 signalLayerUpdate();
2011 }
2012}
2013
Ana Krulece588e312018-09-18 12:32:24 -07002014void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2015 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002016 // Update queue of past composite+present times and determine the
2017 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002018 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002019 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002020 while (!getBE().mCompositePresentTimes.empty()) {
2021 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002022 // Cached values should have been updated before calling this method,
2023 // which helps avoid duplicate syscalls.
2024 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2025 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2026 break;
2027 }
2028 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002029 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030 }
2031
2032 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002033 while (getBE().mCompositePresentTimes.size() > 16) {
2034 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002035 }
2036
Ana Krulece588e312018-09-18 12:32:24 -07002037 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002038}
2039
Ana Krulece588e312018-09-18 12:32:24 -07002040void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2041 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002042 // Integer division and modulo round toward 0 not -inf, so we need to
2043 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002044 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2045 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2046 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002047
Ana Krulec757f63a2019-01-25 10:46:18 -08002048 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002049 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002050 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002051 }
2052
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002053 // Snap the latency to a value that removes scheduling jitter from the
2054 // composition and present times, which often have >1ms of jitter.
2055 // Reducing jitter is important if an app attempts to extrapolate
2056 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002057 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002058 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002059 nsecs_t bias = stats.vsyncPeriod / 2;
2060 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2061 nsecs_t snappedCompositeToPresentLatency =
2062 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063
David Sodman99974d22017-11-28 12:04:33 -08002064 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002065 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2066 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002067 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002068}
2069
David Sodman2b406362017-12-15 13:33:47 -08002070void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002071{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 ATRACE_CALL();
2073 ALOGV("postComposition");
2074
Brian Anderson3546a3f2016-07-14 11:51:14 -07002075 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002076 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002077 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002078 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002079 }
2080
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002081 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002082 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002083
David Sodman73beded2017-11-15 11:56:06 -08002084 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002085 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002086 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002087 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002088 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2089 ->getRenderSurface()
2090 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002091 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002092 } else {
2093 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2094 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002095
David Sodman73beded2017-11-15 11:56:06 -08002096 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002097 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2098 mPreviousPresentFences[0] = displayDevice
2099 ? getHwComposer().getPresentFence(*displayDevice->getId())
2100 : Fence::NO_FENCE;
2101 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002102 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002103
Ana Krulece588e312018-09-18 12:32:24 -07002104 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002105 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002106
David Sodman2b406362017-12-15 13:33:47 -08002107 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002108 // when we started doing work for this frame, but that should be okay
2109 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002110 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002111 CompositorTiming compositorTiming;
2112 {
David Sodman99974d22017-11-28 12:04:33 -08002113 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2114 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002115 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002116
Robert Carr2047fae2016-11-28 14:09:09 -08002117 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002118 bool frameLatched =
2119 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2120 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002121 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002122 recordBufferingStats(layer->getName().string(),
2123 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002124 }
Robert Carr2047fae2016-11-28 14:09:09 -08002125 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002126
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002127 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002128 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002129 }
2130
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002131 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002132 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2133 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002134 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002135 }
2136 }
2137
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002138 if (mAnimCompositionPending) {
2139 mAnimCompositionPending = false;
2140
Brian Anderson4e606e32017-03-16 15:34:57 -07002141 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002142 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002143 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002144 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002145 // The HWC doesn't support present fences, so use the refresh
2146 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002147 const nsecs_t presentTime =
2148 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002149 mAnimFrameTracker.setActualPresentTime(presentTime);
2150 }
2151 mAnimFrameTracker.advanceFrame();
2152 }
Dan Stozab90cf072015-03-05 11:05:59 -08002153
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002154 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002155 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002156 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002157 }
2158
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002159 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002160
Lloyd Pique32cbe282018-10-19 13:09:22 -07002161 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2162 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002163 return;
2164 }
2165
2166 nsecs_t currentTime = systemTime();
2167 if (mHasPoweredOff) {
2168 mHasPoweredOff = false;
2169 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002170 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002171 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002172 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2173 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002174 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002175 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002176 }
David Sodman4a36e932017-11-07 14:29:47 -08002177 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002178 }
David Sodman4a36e932017-11-07 14:29:47 -08002179 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002180
2181 {
2182 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002183 if (mTexturePool.size() < mTexturePoolSize) {
2184 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002185 const size_t offset = mTexturePool.size();
2186 mTexturePool.resize(mTexturePoolSize);
2187 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2188 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002189 } else if (mTexturePool.size() > mTexturePoolSize) {
2190 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2191 const size_t offset = mTexturePoolSize;
2192 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2193 mTexturePool.resize(mTexturePoolSize);
2194 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002195 }
2196 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002197
Ady Abrahambe0f9482019-04-24 15:41:53 -07002198 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallf384e052019-06-12 13:25:07 -07002199
2200 // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
2201 // If we do not lock here, a callback could be sent without all of its SurfaceControls and
2202 // metrics.
2203 {
2204 Mutex::Autolock _l(mStateLock);
2205 mTransactionCompletedThread.sendCallbacks();
2206 }
Ady Abraham8164d482019-01-11 14:47:59 -08002207
Kevin DuBois413287f2019-02-25 08:46:47 -08002208 if (mLumaSampling && mRegionSamplingThread) {
2209 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002210 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002211
2212 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2213 // side-effect of getTotalSize(), so we check that again here
2214 if (ATRACE_ENABLED()) {
2215 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2216 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002217}
2218
Vishnu Nair4351ad52019-02-11 14:13:02 -08002219void SurfaceFlinger::computeLayerBounds() {
2220 for (const auto& pair : mDisplays) {
2221 const auto& displayDevice = pair.second;
2222 const auto display = displayDevice->getCompositionDisplay();
2223 for (const auto& layer : mDrawingState.layersSortedByZ) {
2224 // only consider the layers on the given layer stack
2225 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002226 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002227 }
2228
2229 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2230 }
2231 }
2232}
2233
Mathias Agopiancd60f992012-08-16 16:28:27 -07002234void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002235 ATRACE_CALL();
2236 ALOGV("rebuildLayerStacks");
2237
Mathias Agopiancd60f992012-08-16 16:28:27 -07002238 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002240 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002241 mVisibleRegionsDirty = false;
2242 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002243
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002244 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002245 const auto& displayDevice = pair.second;
2246 auto display = displayDevice->getCompositionDisplay();
2247 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002248 Region opaqueRegion;
2249 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002250 compositionengine::Output::OutputLayers layersSortedByZ;
2251 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002252 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002253 const ui::Transform& tr = displayState.transform;
2254 const Rect bounds = displayState.bounds;
2255 if (displayState.isEnabled) {
2256 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002257
Jeff Sharkey76488112017-02-27 14:15:18 -07002258 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002259 auto compositionLayer = layer->getCompositionLayer();
2260 if (compositionLayer == nullptr) {
2261 return;
2262 }
2263
Lloyd Pique32cbe282018-10-19 13:09:22 -07002264 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002265 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2266 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2267
Lloyd Pique07e33212018-12-18 16:33:37 -08002268 bool needsOutputLayer = false;
2269
Lloyd Piqueef36b002019-01-23 17:52:04 -08002270 if (display->belongsInOutput(layer->getLayerStack(),
2271 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002272 Region drawRegion(tr.transform(
2273 layer->visibleNonTransparentRegion));
2274 drawRegion.andSelf(bounds);
2275 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002276 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002277 }
Chia-I Wu83806892017-11-16 10:50:20 -08002278 }
2279
Lloyd Pique07e33212018-12-18 16:33:37 -08002280 if (needsOutputLayer) {
2281 layersSortedByZ.emplace_back(
2282 display->getOrCreateOutputLayer(displayId, compositionLayer,
2283 layerFE));
2284 deprecated_layersSortedByZ.add(layer);
2285
2286 auto& outputLayerState = layersSortedByZ.back()->editState();
2287 outputLayerState.visibleRegion =
2288 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2289 } else if (displayId) {
2290 // For layers that are being removed from a HWC display,
2291 // and that have queued frames, add them to a a list of
2292 // released layers so we can properly set a fence.
2293 bool hasExistingOutputLayer =
2294 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2295 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2296 mLayersWithQueuedFrames.cend(),
2297 layer) != mLayersWithQueuedFrames.cend();
2298
2299 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002300 layersNeedingFences.add(layer);
2301 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002302 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002303 });
2304 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002305
2306 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2307
2308 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002309 displayDevice->setLayersNeedingFences(layersNeedingFences);
2310
2311 Region undefinedRegion{bounds};
2312 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2313
2314 display->editState().undefinedRegion = undefinedRegion;
2315 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002316 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002317 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002318}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002319
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002320// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002321// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002322// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002323// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002324// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002325// The returned HDR data space is one of
2326// - Dataspace::UNKNOWN
2327// - Dataspace::BT2020_HLG
2328// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002329Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2330 Dataspace* outHdrDataSpace,
2331 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002332 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002333 *outHdrDataSpace = Dataspace::UNKNOWN;
2334
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002335 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002336 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002337 case Dataspace::V0_SCRGB:
2338 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002339 case Dataspace::BT2020:
2340 case Dataspace::BT2020_ITU:
2341 case Dataspace::BT2020_LINEAR:
2342 case Dataspace::DISPLAY_BT2020:
2343 bestDataSpace = Dataspace::DISPLAY_BT2020;
2344 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002345 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002346 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002347 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002348 case Dataspace::BT2020_PQ:
2349 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002350 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002352 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002353 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002354 case Dataspace::BT2020_HLG:
2355 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002356 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002357 // When there's mixed PQ content and HLG content, we set the HDR
2358 // data space to be BT2020_PQ and convert HLG to PQ.
2359 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2360 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002361 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002362 break;
2363 default:
2364 break;
2365 }
Romain Guy54f154a2017-10-24 21:40:32 +01002366 }
2367
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002368 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002369}
2370
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2373 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002374 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2375 *outMode = ColorMode::NATIVE;
2376 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002377 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002378 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002379 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002380
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002381 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002382 bool isHdrClientComposition = false;
2383 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002385 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2386
Peiyong Lina3ea5592019-02-10 14:45:00 -08002387 switch (mForceColorMode) {
2388 case ColorMode::SRGB:
2389 bestDataSpace = Dataspace::V0_SRGB;
2390 break;
2391 case ColorMode::DISPLAY_P3:
2392 bestDataSpace = Dataspace::DISPLAY_P3;
2393 break;
2394 default:
2395 break;
2396 }
2397
Peiyong Lindfde5112018-06-05 10:58:41 -07002398 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002399 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2400 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002401 if (isHdr) {
2402 bestDataSpace = hdrDataSpace;
2403 }
2404
Chia-I Wu0d711262018-05-21 15:19:35 -07002405 RenderIntent intent;
2406 switch (mDisplayColorSetting) {
2407 case DisplayColorSetting::MANAGED:
2408 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002409 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002410 break;
2411 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002412 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002413 break;
2414 default: // vendor display color setting
2415 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2416 break;
2417 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002418
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002419 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002420}
2421
Lloyd Pique32cbe282018-10-19 13:09:22 -07002422void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2423 auto display = displayDevice->getCompositionDisplay();
2424 const auto& displayState = display->getState();
2425
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002426 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002427 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2428 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002429
David Sodmanfa9b2af2017-12-24 13:28:59 -08002430 // If nothing has changed (!dirty), don't recompose.
2431 // If something changed, but we don't currently have any visible layers,
2432 // and didn't when we last did a composition, then skip it this time.
2433 // The second rule does two things:
2434 // - When all layers are removed from a display, we'll emit one black
2435 // frame, then nothing more until we get new layers.
2436 // - When a display is created with a private layer stack, we won't
2437 // emit any black frames until a layer is added to the layer stack.
2438 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002439
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 const char flagPrefix[] = {'-', '+'};
2441 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002442 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2443 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2444 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2445 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002446
Lloyd Pique31cb2942018-10-19 17:23:03 -07002447 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002448
David Sodmanfa9b2af2017-12-24 13:28:59 -08002449 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002450 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002451 }
2452}
2453
Lloyd Pique32cbe282018-10-19 13:09:22 -07002454void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2455 auto display = displayDevice->getCompositionDisplay();
2456 const auto& displayState = display->getState();
2457
2458 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002459 return;
David Sodman2b406362017-12-15 13:33:47 -08002460 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002461
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002462 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002464 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002465}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002466
Lloyd Pique32cbe282018-10-19 13:09:22 -07002467void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002468 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002469 ALOGV("doComposition");
2470
Lloyd Pique32cbe282018-10-19 13:09:22 -07002471 auto display = displayDevice->getCompositionDisplay();
2472 const auto& displayState = display->getState();
2473
2474 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002475 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002476 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002477
David Sodmanfa9b2af2017-12-24 13:28:59 -08002478 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002479 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002480
Lloyd Pique32cbe282018-10-19 13:09:22 -07002481 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002482 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002483 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002484 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002485}
2486
David Sodmanfa9b2af2017-12-24 13:28:59 -08002487void SurfaceFlinger::postFrame()
2488{
2489 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002490 const auto display = getDefaultDisplayDeviceLocked();
2491 if (display && getHwComposer().isConnected(*display->getId())) {
2492 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002493 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2494 logFrameStats();
2495 }
2496 }
2497}
2498
Lloyd Pique32cbe282018-10-19 13:09:22 -07002499void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002500 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002501 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002502
Lloyd Pique32cbe282018-10-19 13:09:22 -07002503 auto display = displayDevice->getCompositionDisplay();
2504 const auto& displayState = display->getState();
2505 const auto displayId = display->getId();
2506
Lloyd Pique32cbe282018-10-19 13:09:22 -07002507 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002508 if (displayId) {
2509 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002510 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002511 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002512 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002513 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002514 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002515
Chia-I Wu7b549592017-11-15 09:14:57 -08002516 // The layer buffer from the previous frame (if any) is released
2517 // by HWC only when the release fence from this frame (if any) is
2518 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002519 if (layer->getState().hwc) {
2520 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002521 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002522 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2523 usedClientComposition =
2524 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002525 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002526
2527 // If the layer was client composited in the previous frame, we
2528 // need to merge with the previous client target acquire fence.
2529 // Since we do not track that, always merge with the current
2530 // client target acquire fence when it is available, even though
2531 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002532 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002533 releaseFence =
2534 Fence::merge("LayerRelease", releaseFence,
2535 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002536 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002537
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002538 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002539 }
Chia-I Wu83806892017-11-16 10:50:20 -08002540
2541 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002542 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002543 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002544 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002546 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002547 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002548 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002549 }
2550 }
2551
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 if (displayId) {
2553 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002554 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002555 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002556}
2557
Mathias Agopian87baae12012-07-31 12:38:26 -07002558void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002559{
Mathias Agopian841cde52012-03-01 15:44:37 -08002560 ATRACE_CALL();
2561
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002562 // here we keep a copy of the drawing state (that is the state that's
2563 // going to be overwritten by handleTransactionLocked()) outside of
2564 // mStateLock so that the side-effects of the State assignment
2565 // don't happen with mStateLock held (which can cause deadlocks).
2566 State drawingState(mDrawingState);
2567
Mathias Agopianca4d3602011-05-19 15:38:14 -07002568 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002569 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570
Mathias Agopianca4d3602011-05-19 15:38:14 -07002571 // Here we're guaranteed that some transaction flags are set
2572 // so we can call handleTransactionLocked() unconditionally.
2573 // We call getTransactionFlags(), which will also clear the flags,
2574 // with mStateLock held to guarantee that mCurrentState won't change
2575 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002576
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002577 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002578 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002579 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002580
Mathias Agopianca4d3602011-05-19 15:38:14 -07002581 mDebugInTransaction = 0;
2582 invalidateHwcGeometry();
2583 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002584}
2585
Lloyd Piqueba04e622017-12-14 17:11:26 -08002586void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2587 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 const std::optional<DisplayIdentificationInfo> info =
2589 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002590
Dominik Laskowski075d3172018-05-24 15:50:06 -07002591 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002592 continue;
2593 }
2594
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002597 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002598 mPhysicalDisplayTokens[info->id] = new BBinder();
2599 DisplayDeviceState state;
2600 state.displayId = info->id;
2601 state.isSecure = true; // All physical displays are currently considered secure.
2602 state.displayName = info->name;
2603 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2604 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002605 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002606 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002607 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002608
Dominik Laskowski075d3172018-05-24 15:50:06 -07002609 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2610 if (index >= 0) {
2611 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2612 mInterceptor->saveDisplayDeletion(state.sequenceId);
2613 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002614 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002615 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002616 }
2617
2618 processDisplayChangesLocked();
2619 }
2620
2621 mPendingHotplugEvents.clear();
2622}
2623
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002624void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002625 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2626 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002627}
2628
Lloyd Pique99d3da52018-01-22 17:48:03 -08002629sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002631 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 const sp<IGraphicBufferProducer>& producer) {
2633 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002634 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002635 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002636 creationArgs.isSecure = state.isSecure;
2637 creationArgs.displaySurface = dispSurface;
2638 creationArgs.hasWideColorGamut = false;
2639 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002640
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002641 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002642 creationArgs.isPrimary = isInternalDisplay;
2643
2644 if (useColorManagement && displayId) {
2645 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002646 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002647 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002648 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002650
Dominik Laskowski7e045462018-05-30 13:02:02 -07002651 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002652 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002653 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002654 }
tangrobin6753a022018-08-10 10:58:54 +08002655 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002656
Dominik Laskowski075d3172018-05-24 15:50:06 -07002657 if (displayId) {
2658 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002659 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002660 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002661 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002662
Lloyd Pique90c115d2018-09-18 21:39:42 -07002663 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002664 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002665 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002666
Lloyd Pique99d3da52018-01-22 17:48:03 -08002667 // Make sure that composition can never be stalled by a virtual display
2668 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002669 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002670 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2672 }
2673
Dominik Laskowski075d3172018-05-24 15:50:06 -07002674 creationArgs.displayInstallOrientation =
2675 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002676
Lloyd Pique99d3da52018-01-22 17:48:03 -08002677 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002678 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002679
Lloyd Pique90c115d2018-09-18 21:39:42 -07002680 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002681
2682 if (maxFrameBufferAcquiredBuffers >= 3) {
2683 nativeWindowSurface->preallocateBuffers();
2684 }
2685
2686 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002687 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002688 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002689 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002690 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002691 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002692 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2693 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694 if (!state.isVirtual()) {
2695 LOG_ALWAYS_FATAL_IF(!displayId);
2696 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002697 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002698
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002699 display->setLayerStack(state.layerStack);
2700 display->setProjection(state.orientation, state.viewport, state.frame);
2701 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002702
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002703 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002704}
2705
Lloyd Pique347200f2017-12-14 17:00:15 -08002706void SurfaceFlinger::processDisplayChangesLocked() {
2707 // here we take advantage of Vector's copy-on-write semantics to
2708 // improve performance by skipping the transaction entirely when
2709 // know that the lists are identical
2710 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2711 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2712 if (!curr.isIdenticalTo(draw)) {
2713 mVisibleRegionsDirty = true;
2714 const size_t cc = curr.size();
2715 size_t dc = draw.size();
2716
2717 // find the displays that were removed
2718 // (ie: in drawing state but not in current state)
2719 // also handle displays that changed
2720 // (ie: displays that are in both lists)
2721 for (size_t i = 0; i < dc;) {
2722 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2723 if (j < 0) {
2724 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002725 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002726 // Save display ID before disconnecting.
2727 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002728 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002729
2730 if (!display->isVirtual()) {
2731 LOG_ALWAYS_FATAL_IF(!displayId);
2732 dispatchDisplayHotplugEvent(displayId->value, false);
2733 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002735
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002736 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002737 } else {
2738 // this display is in both lists. see if something changed.
2739 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002740 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002741 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2742 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2743 if (state_binder != draw_binder) {
2744 // changing the surface is like destroying and
2745 // recreating the DisplayDevice, so we just remove it
2746 // from the drawing state, so that it get re-added
2747 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002748 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002749 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002750 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002751 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002752 mDrawingState.displays.removeItemsAt(i);
2753 dc--;
2754 // at this point we must loop to the next item
2755 continue;
2756 }
2757
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002758 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002759 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 }
2762 if ((state.orientation != draw[i].orientation) ||
2763 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002764 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002765 }
2766 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 }
2769 }
2770 }
2771 ++i;
2772 }
2773
2774 // find displays that were added
2775 // (ie: in current state but not in drawing state)
2776 for (size_t i = 0; i < cc; i++) {
2777 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2778 const DisplayDeviceState& state(curr[i]);
2779
Lloyd Pique542307f2018-10-19 13:24:08 -07002780 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002781 sp<IGraphicBufferProducer> producer;
2782 sp<IGraphicBufferProducer> bqProducer;
2783 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002784 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002785
Dominik Laskowski075d3172018-05-24 15:50:06 -07002786 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002787 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002788 // Virtual displays without a surface are dormant:
2789 // they have external state (layer stack, projection,
2790 // etc.) but no internal state (i.e. a DisplayDevice).
2791 if (state.surface != nullptr) {
2792 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002793 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002794 int width = 0;
2795 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2796 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2797 int height = 0;
2798 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2799 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2800 int intFormat = 0;
2801 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2802 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002803 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002804
Dominik Laskowski075d3172018-05-24 15:50:06 -07002805 displayId =
2806 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002807 }
2808
2809 // TODO: Plumb requested format back up to consumer
2810
2811 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002812 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002813 bqProducer, bqConsumer,
2814 state.displayName);
2815
2816 dispSurface = vds;
2817 producer = vds;
2818 }
2819 } else {
2820 ALOGE_IF(state.surface != nullptr,
2821 "adding a supported display, but rendering "
2822 "surface is provided (%p), ignoring it",
2823 state.surface.get());
2824
Dominik Laskowski075d3172018-05-24 15:50:06 -07002825 displayId = state.displayId;
2826 LOG_ALWAYS_FATAL_IF(!displayId);
2827 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002828 producer = bqProducer;
2829 }
2830
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002831 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002832 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002833 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002834 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002835 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002836 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002837 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002838 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002839 }
2840 }
2841 }
2842 }
2843 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002844
2845 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002846}
2847
Mathias Agopian87baae12012-07-31 12:38:26 -07002848void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002849{
Dan Stoza7dde5992015-05-22 09:51:44 -07002850 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002851 mCurrentState.traverseInZOrder([](Layer* layer) {
2852 layer->notifyAvailableFrames();
2853 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002854
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855 /*
2856 * Traversal of the children
2857 * (perform the transaction for each of them if needed)
2858 */
2859
Marissa Wall06255332019-03-27 13:48:27 -07002860 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002861 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002862 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002863 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864
2865 const uint32_t flags = layer->doTransaction(0);
2866 if (flags & Layer::eVisibleRegion)
2867 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002868
2869 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002870 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002871 }
Robert Carr2047fae2016-11-28 14:09:09 -08002872 });
Marissa Wall06255332019-03-27 13:48:27 -07002873 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002874 }
2875
2876 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002877 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002878 */
2879
Mathias Agopiane57f2922012-08-09 16:29:12 -07002880 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002881 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002882 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002883 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002885 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002886 // The transform hint might have changed for some layers
2887 // (either because a display has changed, or because a layer
2888 // as changed).
2889 //
2890 // Walk through all the layers in currentLayers,
2891 // and update their transform hint.
2892 //
2893 // If a layer is visible only on a single display, then that
2894 // display is used to calculate the hint, otherwise we use the
2895 // default display.
2896 //
2897 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2898 // the hint is set before we acquire a buffer from the surface texture.
2899 //
2900 // NOTE: layer transactions have taken place already, so we use their
2901 // drawing state. However, SurfaceFlinger's own transaction has not
2902 // happened yet, so we must use the current state layer list
2903 // (soon to become the drawing state list).
2904 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002905 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002906 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002907 bool first = true;
2908 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002909 // NOTE: we rely on the fact that layers are sorted by
2910 // layerStack first (so we don't have to traverse the list
2911 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002912 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002913 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002914 currentlayerStack = layerStack;
2915 // figure out if this layerstack is mirrored
2916 // (more than one display) if so, pick the default display,
2917 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002918 hintDisplay = nullptr;
2919 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002920 if (display->getCompositionDisplay()
2921 ->belongsInOutput(layer->getLayerStack(),
2922 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002923 if (hintDisplay) {
2924 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002925 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002926 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002928 }
2929 }
2930 }
2931 }
Chet Haase91d25932013-04-11 15:24:55 -07002932
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002933 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002934 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2935 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002936
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002937 // could be null when this layer is using a layerStack
2938 // that is not visible on any display. Also can occur at
2939 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002940 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002941 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002942
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002943 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002944 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002945 if (hintDisplay) {
2946 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002947 }
Robert Carr2047fae2016-11-28 14:09:09 -08002948
2949 first = false;
2950 });
Mathias Agopian84300952012-11-21 16:02:13 -08002951 }
2952
2953
Mathias Agopian3559b072012-08-15 13:46:03 -07002954 /*
2955 * Perform our own transaction if needed
2956 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002957
2958 if (mLayersAdded) {
2959 mLayersAdded = false;
2960 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002961 mVisibleRegionsDirty = true;
2962 }
2963
2964 // some layers might have been removed, so
2965 // we need to update the regions they're exposing.
2966 if (mLayersRemoved) {
2967 mLayersRemoved = false;
2968 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002969 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002970 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002971 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002972 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002973 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002974 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002975 }
Robert Carr2047fae2016-11-28 14:09:09 -08002976 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002977 }
2978
Vishnu Nairec0ab382019-02-13 15:32:56 -08002979 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002981}
2982
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002983void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002984 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002985 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002986 return;
2987 }
2988
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002989 if (mVisibleRegionsDirty || mInputInfoChanged) {
2990 mInputInfoChanged = false;
2991 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002992 } else if (mInputWindowCommands.syncInputWindows) {
2993 // If the caller requested to sync input windows, but there are no
2994 // changes to input windows, notify immediately.
2995 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002996 }
2997
2998 executeInputWindowCommands();
2999}
3000
3001void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003002 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07003003
3004 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3005 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003006 // When calculating the screen bounds we ignore the transparent region since it may
3007 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003008 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003009 }
3010 });
chaviw291d88a2019-02-14 10:33:58 -08003011
3012 mInputFlinger->setInputWindows(inputHandles,
3013 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3014 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003015}
3016
Vishnu Nairec0ab382019-02-13 15:32:56 -08003017void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07003018 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08003019 mPendingInputWindowCommands.clear();
3020}
3021
chaviwfbe5d9c2018-12-26 12:23:37 -08003022void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003023 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3024 if (transferTouchFocusCommand.fromToken != nullptr &&
3025 transferTouchFocusCommand.toToken != nullptr &&
3026 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3027 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3028 transferTouchFocusCommand.toToken);
3029 }
3030 }
3031
3032 mInputWindowCommands.clear();
3033}
3034
Riley Andrews03414a12014-07-01 14:22:59 -07003035void SurfaceFlinger::updateCursorAsync()
3036{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003037 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003038 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003039 continue;
3040 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3043 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003044 }
3045 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046}
3047
chaviw61626f22018-11-15 16:26:27 -08003048void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3049 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003050 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003051 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003052 }
3053 layer->releasePendingBuffer(systemTime());
3054}
3055
Mathias Agopian4fec8732012-06-29 14:12:52 -07003056void SurfaceFlinger::commitTransaction()
3057{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003058 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003060 for (const auto& l : mLayersPendingRemoval) {
3061 recordBufferingStats(l->getName().string(),
3062 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003063
Lloyd Pique07e33212018-12-18 16:33:37 -08003064 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003065 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003066 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003067 }
chaviw74d90ad2019-04-26 14:45:26 -07003068
3069 // If the layer has been removed and has no parent, then it will not be reachable
3070 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3071 // ensure we can copy its current to drawing state.
3072 if (!l->getParent()) {
3073 mOffscreenLayers.emplace(l.get());
3074 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003075 }
3076 mLayersPendingRemoval.clear();
3077 }
3078
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003079 // If this transaction is part of a window animation then the next frame
3080 // we composite should be considered an animation as well.
3081 mAnimCompositionPending = mAnimTransactionPending;
3082
Nataniel Borges2b796da2019-02-15 13:32:18 -08003083 withTracingLock([&]() {
3084 mDrawingState = mCurrentState;
3085 // clear the "changed" flags in current state
3086 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003087
chaviw74d90ad2019-04-26 14:45:26 -07003088 mDrawingState.traverseInZOrder([&](Layer* layer) {
3089 layer->commitChildList();
3090
3091 // If the layer can be reached when traversing mDrawingState, then the layer is no
3092 // longer offscreen. Remove the layer from the offscreenLayer set.
3093 if (mOffscreenLayers.count(layer)) {
3094 mOffscreenLayers.erase(layer);
3095 }
3096 });
3097
3098 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003099 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003100
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003101 mTransactionPending = false;
3102 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003103 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003104}
3105
Nataniel Borges2b796da2019-02-15 13:32:18 -08003106void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3107 if (mTracingEnabledChanged) {
3108 mTracingEnabled = mTracing.isEnabled();
3109 mTracingEnabledChanged = false;
3110 }
3111
3112 // Synchronize with Tracing thread
3113 std::unique_lock<std::mutex> lock;
3114 if (mTracingEnabled) {
3115 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3116 }
3117
3118 lockedOperation();
3119
3120 // Synchronize with Tracing thread
3121 if (mTracingEnabled) {
3122 lock.unlock();
3123 }
3124}
3125
chaviw74d90ad2019-04-26 14:45:26 -07003126void SurfaceFlinger::commitOffscreenLayers() {
3127 for (Layer* offscreenLayer : mOffscreenLayers) {
3128 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3129 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3130 if (!trFlags) return;
3131
3132 layer->doTransaction(0);
3133 layer->commitChildList();
3134 });
3135 }
3136}
3137
Lloyd Pique32cbe282018-10-19 13:09:22 -07003138void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003139 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003140 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003141 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003142
Lloyd Pique32cbe282018-10-19 13:09:22 -07003143 auto display = displayDevice->getCompositionDisplay();
3144
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003145 Region aboveOpaqueLayers;
3146 Region aboveCoveredLayers;
3147 Region dirty;
3148
Mathias Agopian87baae12012-07-31 12:38:26 -07003149 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003150
Robert Carr2047fae2016-11-28 14:09:09 -08003151 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003152 // start with the whole surface at its current location
3153 const Layer::State& s(layer->getDrawingState());
3154
Jesse Hall01e29052013-02-19 16:13:35 -08003155 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003156 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003157 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003158 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003159
Mathias Agopianab028732010-03-16 16:41:46 -07003160 /*
3161 * opaqueRegion: area of a surface that is fully opaque.
3162 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003163 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003164
3165 /*
3166 * visibleRegion: area of a surface that is visible on screen
3167 * and not fully transparent. This is essentially the layer's
3168 * footprint minus the opaque regions above it.
3169 * Areas covered by a translucent surface are considered visible.
3170 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003172
3173 /*
3174 * coveredRegion: area of a surface that is covered by all
3175 * visible regions above it (which includes the translucent areas).
3176 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003178
Jesse Halla8026d22012-09-25 13:25:04 -07003179 /*
3180 * transparentRegion: area of a surface that is hinted to be completely
3181 * transparent. This is only used to tell when the layer has no visible
3182 * non-transparent regions and can be removed from the layer list. It
3183 * does not affect the visibleRegion of this layer or any layers
3184 * beneath it. The hint may not be correct if apps don't respect the
3185 * SurfaceView restrictions (which, sadly, some don't).
3186 */
3187 Region transparentRegion;
3188
Mathias Agopianab028732010-03-16 16:41:46 -07003189
3190 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003191 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003192 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003193 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003194
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003196 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003197 if (!visibleRegion.isEmpty()) {
3198 // Remove the transparent area from the visible region
3199 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003200 if (tr.preserveRects()) {
3201 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003202 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003203 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003204 // transformation too complex, can't do the
3205 // transparent region optimization.
3206 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003207 }
Mathias Agopianab028732010-03-16 16:41:46 -07003208 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003209
Mathias Agopianab028732010-03-16 16:41:46 -07003210 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003211 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003212 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003213 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003214 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003215 // the opaque region is the layer's footprint
3216 opaqueRegion = visibleRegion;
3217 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218 }
3219 }
3220
Robert Carre5f4f692018-01-12 13:12:28 -08003221 if (visibleRegion.isEmpty()) {
3222 layer->clearVisibilityRegions();
3223 return;
3224 }
3225
Mathias Agopianab028732010-03-16 16:41:46 -07003226 // Clip the covered region to the visible region
3227 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3228
3229 // Update aboveCoveredLayers for next (lower) layer
3230 aboveCoveredLayers.orSelf(visibleRegion);
3231
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003232 // subtract the opaque region covered by the layers above us
3233 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003234
3235 // compute this layer's dirty region
3236 if (layer->contentDirty) {
3237 // we need to invalidate the whole region
3238 dirty = visibleRegion;
3239 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003240 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 layer->contentDirty = false;
3242 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003243 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003244 * the exposed region consists of two components:
3245 * 1) what's VISIBLE now and was COVERED before
3246 * 2) what's EXPOSED now less what was EXPOSED before
3247 *
3248 * note that (1) is conservative, we start with the whole
3249 * visible region but only keep what used to be covered by
3250 * something -- which mean it may have been exposed.
3251 *
3252 * (2) handles areas that were not covered by anything but got
3253 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003254 */
Mathias Agopianab028732010-03-16 16:41:46 -07003255 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003256 const Region oldVisibleRegion = layer->visibleRegion;
3257 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003258 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3259 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003260 }
3261 dirty.subtractSelf(aboveOpaqueLayers);
3262
3263 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003264 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265
Mathias Agopianab028732010-03-16 16:41:46 -07003266 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003267 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003268
Jesse Halla8026d22012-09-25 13:25:04 -07003269 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003270 layer->setVisibleRegion(visibleRegion);
3271 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003272 layer->setVisibleNonTransparentRegion(
3273 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003274 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003275
Mathias Agopian87baae12012-07-31 12:38:26 -07003276 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003277}
3278
Chia-I Wuab0c3192017-08-01 11:29:00 -07003279void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003280 for (const auto& [token, displayDevice] : mDisplays) {
3281 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003282 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003283 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003284 }
3285 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003286}
3287
Dan Stoza6b9454d2014-11-07 16:00:59 -08003288bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003289{
Ady Abraham09bd3922019-04-08 10:44:56 -07003290 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003291 ALOGV("handlePageFlip");
3292
Brian Andersond6927fb2016-07-23 23:37:30 -07003293 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003294
Mathias Agopian4fec8732012-06-29 14:12:52 -07003295 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003296 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003297 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003298
3299 // Store the set of layers that need updates. This set must not change as
3300 // buffers are being latched, as this could result in a deadlock.
3301 // Example: Two producers share the same command stream and:
3302 // 1.) Layer 0 is latched
3303 // 2.) Layer 0 gets a new frame
3304 // 2.) Layer 1 gets a new frame
3305 // 3.) Layer 1 is latched.
3306 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3307 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003308 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003309 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003310 frameQueued = true;
Alec Mouri746654a2019-06-06 13:28:34 -07003311 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003312 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003313 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003314 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003315 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003316 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003317 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003318 } else {
3319 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003320 }
Robert Carr2047fae2016-11-28 14:09:09 -08003321 });
3322
Lloyd Piquef2c79392018-12-20 16:23:33 -08003323 if (!mLayersWithQueuedFrames.empty()) {
3324 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3325 // writes to Layer current state. See also b/119481871
3326 Mutex::Autolock lock(mStateLock);
3327
3328 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003329 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003330 mLayersPendingRefresh.push_back(layer);
3331 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003332 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003333 if (layer->isBufferLatched()) {
3334 newDataLatched = true;
3335 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003336 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003337 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003338
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003339 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003340
3341 // If we will need to wake up at some time in the future to deal with a
3342 // queued frame that shouldn't be displayed during this vsync period, wake
3343 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003344 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003345 signalLayerUpdate();
3346 }
3347
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003348 // enter boot animation on first buffer latch
3349 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3350 ALOGI("Enter boot animation");
3351 mBootStage = BootStage::BOOTANIMATION;
3352 }
3353
Dan Stoza6b9454d2014-11-07 16:00:59 -08003354 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003355 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003356}
3357
Mathias Agopianad456f92011-01-13 17:53:01 -08003358void SurfaceFlinger::invalidateHwcGeometry()
3359{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003360 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003361}
3362
Lloyd Pique32cbe282018-10-19 13:09:22 -07003363void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003364 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003365 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003366 // We only need to actually compose the display if:
3367 // 1) It is being handled by hardware composer, which may need this to
3368 // keep its virtual display state machine in sync, or
3369 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003370 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003371 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003372 return;
3373 }
3374
Dan Stoza9e56aa02015-11-02 13:00:03 -08003375 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003376 base::unique_fd readyFence;
3377 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003378
3379 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003380 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003381}
3382
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003383bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3384 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003385 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003386 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003387
Lloyd Pique32cbe282018-10-19 13:09:22 -07003388 auto display = displayDevice->getCompositionDisplay();
3389 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003390 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003391 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003392 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003393
3394 const Region bounds(displayState.bounds);
3395 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003396 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003397 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003398
Chia-I Wu8e50e692018-05-04 10:12:37 -07003399 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003400
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003401 renderengine::DisplaySettings clientCompositionDisplay;
3402 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3403 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003404 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003405
Dan Stoza9e56aa02015-11-02 13:00:03 -08003406 if (hasClientComposition) {
3407 ALOGV("hasClientComposition");
3408
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003409 if (displayDevice->isPrimary() && supportProtectedContent) {
3410 bool needsProtected = false;
3411 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3412 // If the layer is a protected layer, mark protected context is needed.
3413 if (layer->isProtected()) {
3414 needsProtected = true;
3415 break;
3416 }
3417 }
Peiyong Lin52010312019-05-02 14:22:16 -07003418 if (needsProtected != renderEngine.isProtected()) {
3419 renderEngine.useProtectedContext(needsProtected);
3420 }
3421 if (needsProtected != display->getRenderSurface()->isProtected() &&
3422 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003423 display->getRenderSurface()->setProtected(needsProtected);
3424 }
3425 }
3426
Alec Mouri6338c9d2019-02-07 16:57:51 -08003427 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003428
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003429 if (buf == nullptr) {
3430 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3431 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003432 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003433 return false;
3434 }
3435
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003436 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3437 clientCompositionDisplay.clip = displayState.scissor;
3438 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003439 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003440 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003441
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003442 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003443 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003444 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003445 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003446 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003447 clientCompositionDisplay.outputDataspace = outputDataspace;
3448 clientCompositionDisplay.maxLuminance =
3449 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003450
Lloyd Pique441d5042018-10-18 16:49:51 -07003451 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003452 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003453 getHwComposer()
3454 .hasDisplayCapability(displayId,
3455 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003456
Peiyong Lind3788632018-09-18 16:01:31 -07003457 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003458 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3459 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003460 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003461 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003462 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003463
Mathias Agopian85d751c2012-08-29 16:59:24 -07003464 /*
3465 * and then, render the layers targeted at the framebuffer
3466 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003467
Dan Stoza9e56aa02015-11-02 13:00:03 -08003468 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003469 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003470 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003471 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003472 const Region viewportRegion(displayState.viewport);
3473 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003474 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003475 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003476 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003477 switch (layer->getCompositionType(displayDevice)) {
3478 case Hwc2::IComposerClient::Composition::CURSOR:
3479 case Hwc2::IComposerClient::Composition::DEVICE:
3480 case Hwc2::IComposerClient::Composition::SIDEBAND:
3481 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003482 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003483 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003484 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003485 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003486 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003487 // never clear the very first layer since we're
3488 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003489 renderengine::LayerSettings layerSettings;
3490 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003491 bool prepared =
3492 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3493 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003494
3495 if (prepared) {
3496 layerSettings.source.buffer.buffer = nullptr;
3497 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3498 layerSettings.alpha = half(0.0);
3499 layerSettings.disableBlending = true;
3500 clientCompositionLayers.push_back(layerSettings);
3501 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003502 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003503 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003504 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003505 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003506 renderengine::LayerSettings layerSettings;
3507 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003508 layer->prepareClientLayer(renderArea, clip, clearRegion,
3509 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003510 if (prepared) {
3511 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003512 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003513 break;
3514 }
3515 default:
3516 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003517 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003518 } else {
3519 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003520 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003521 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003522 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003523
Alec Mouri820c7402019-01-23 13:02:39 -08003524 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003525 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003526 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003527
3528 // We boost GPU frequency here because there will be color spaces conversion
3529 // and it's expensive. We boost the GPU frequency so that GPU composition can
3530 // finish in time. We must reset GPU frequency afterwards, because high frequency
3531 // consumes extra battery.
3532 const bool expensiveRenderingExpected =
3533 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3534 if (expensiveRenderingExpected && displayId) {
3535 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3536 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003537 if (!debugRegion.isEmpty()) {
3538 Region::const_iterator it = debugRegion.begin();
3539 Region::const_iterator end = debugRegion.end();
3540 while (it != end) {
3541 const Rect& rect = *it++;
3542 renderengine::LayerSettings layerSettings;
3543 layerSettings.source.buffer.buffer = nullptr;
3544 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3545 layerSettings.geometry.boundaries = rect.toFloatRect();
3546 layerSettings.alpha = half(1.0);
3547 clientCompositionLayers.push_back(layerSettings);
3548 }
3549 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003550 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003551 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3552 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003553 } else if (displayId) {
3554 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003555 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003556 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003557}
3558
Chia-I Wu28e3a252018-09-07 12:05:02 -07003559void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003560 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003561 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562}
3563
Robert Carrc0df3122019-04-11 13:18:21 -07003564status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3565 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3566 const sp<IBinder>& parentHandle,
3567 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003568 // add this layer to the current state list
3569 {
3570 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003571 sp<Layer> parent;
3572 if (parentHandle != nullptr) {
3573 parent = fromHandle(parentHandle);
3574 if (parent == nullptr) {
3575 return NAME_NOT_FOUND;
3576 }
3577 } else {
3578 parent = parentLayer;
3579 }
3580
Robert Carr1f0a16a2016-10-24 16:27:39 -07003581 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003582 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3583 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003584 return NO_MEMORY;
3585 }
Robert Carrc0df3122019-04-11 13:18:21 -07003586
3587 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3588
Robert Carrb89ea9d2018-12-10 13:01:14 -08003589 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003590 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003591 } else if (parent == nullptr) {
3592 lbc->onRemovedFromCurrentState();
3593 } else if (parent->isRemovedFromCurrentState()) {
3594 parent->addChild(lbc);
3595 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003596 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003597 parent->addChild(lbc);
3598 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003599
Yiwei Zhang243b3782018-05-15 17:40:04 -07003600 if (gbc != nullptr) {
3601 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3602 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3603 mMaxGraphicBufferProducerListSize,
3604 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3605 mGraphicBufferProducerList.size(),
3606 mMaxGraphicBufferProducerListSize, mNumLayers);
3607 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003608 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003609 }
3610
Mathias Agopian96f08192010-06-02 23:28:45 -07003611 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003612 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003613
Dan Stoza7d89d062015-04-30 13:29:25 -07003614 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003615}
3616
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003617uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003618 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003619}
3620
Mathias Agopian3f844832013-08-07 21:24:32 -07003621uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003622 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003623}
3624
Mathias Agopian3f844832013-08-07 21:24:32 -07003625uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003626 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003627}
3628
3629uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003630 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003631 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003632 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003633 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003634 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635 }
3636 return old;
3637}
3638
Marissa Wall713b63f2018-10-17 15:42:43 -07003639bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003640 // to prevent onHandleDestroyed from being called while the lock is held,
3641 // we must keep a copy of the transactions (specifically the composer
3642 // states) around outside the scope of the lock
3643 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003644 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003645 {
3646 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003647
Valerie Haufce31b82019-04-30 16:41:14 -07003648 auto it = mTransactionQueues.begin();
3649 while (it != mTransactionQueues.end()) {
3650 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003651
Valerie Haufce31b82019-04-30 16:41:14 -07003652 while (!transactionQueue.empty()) {
3653 const auto& transaction = transactionQueue.front();
3654 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3655 transaction.states)) {
3656 setTransactionFlags(eTransactionFlushNeeded);
3657 break;
3658 }
3659 transactions.push_back(transaction);
3660 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3661 mPendingInputWindowCommands, transaction.desiredPresentTime,
3662 transaction.buffer, transaction.callback,
3663 transaction.postTime, transaction.privileged,
3664 /*isMainThread*/ true);
3665 transactionQueue.pop();
3666 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003667 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003668
Valerie Haufce31b82019-04-30 16:41:14 -07003669 if (transactionQueue.empty()) {
3670 it = mTransactionQueues.erase(it);
3671 mTransactionCV.broadcast();
3672 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003673 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003674 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003675 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003676 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003677 return flushedATransaction;
3678}
3679
3680bool SurfaceFlinger::transactionFlushNeeded() {
3681 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003682}
3683
chaviwca27f252018-02-06 16:46:39 -08003684bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3685 for (const ComposerState& state : states) {
3686 // Here we need to check that the interface we're given is indeed
3687 // one of our own. A malicious client could give us a nullptr
3688 // IInterface, or one of its own or even one of our own but a
3689 // different type. All these situations would cause us to crash.
3690 if (state.client == nullptr) {
3691 return true;
3692 }
3693
3694 sp<IBinder> binder = IInterface::asBinder(state.client);
3695 if (binder == nullptr) {
3696 return true;
3697 }
3698
3699 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3700 return true;
3701 }
3702 }
3703 return false;
3704}
3705
Marissa Wall17b4e452018-12-26 16:32:34 -08003706bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3707 const Vector<ComposerState>& states) {
Ady Abraham83127b72019-06-12 17:11:12 -07003708 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003709 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3710 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3711 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3712 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3713 return false;
3714 }
3715
Marissa Wall713b63f2018-10-17 15:42:43 -07003716 for (const ComposerState& state : states) {
3717 const layer_state_t& s = state.state;
3718 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3719 continue;
3720 }
3721 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003722 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003723 }
3724 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003725 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003726}
3727
3728void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3729 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003730 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003731 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003732 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003733 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003734 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003735 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003736
Valerie Haubc6ddb12019-03-08 11:10:15 -08003737 const int64_t postTime = systemTime();
3738
Robert Carr14167e02019-02-13 13:50:55 -08003739 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3740
Mathias Agopian698c0872011-06-28 19:09:31 -07003741 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003742
chaviwca27f252018-02-06 16:46:39 -08003743 if (containsAnyInvalidClientState(states)) {
3744 return;
3745 }
3746
Marissa Wall713b63f2018-10-17 15:42:43 -07003747 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003748 auto itr = mTransactionQueues.find(applyToken);
3749 // if this is an animation frame, wait until prior animation frame has
3750 // been applied by SF
3751 if (flags & eAnimation) {
3752 while (itr != mTransactionQueues.end()) {
3753 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3754 if (CC_UNLIKELY(err != NO_ERROR)) {
3755 ALOGW_IF(err == TIMED_OUT,
3756 "setTransactionState timed out "
3757 "waiting for animation frame to apply");
3758 break;
3759 }
3760 itr = mTransactionQueues.find(applyToken);
3761 }
3762 }
3763 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003764 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003765 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003766 uncacheBuffer, listenerCallbacks, postTime,
3767 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003768 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003769 return;
3770 }
3771
Valerie Haubc6ddb12019-03-08 11:10:15 -08003772 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003773 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003774}
3775
3776void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003777 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003778 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003779 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003780 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003781 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003782 const int64_t postTime, bool privileged,
3783 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003784 uint32_t transactionFlags = 0;
3785
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003786 if (flags & eAnimation) {
3787 // For window updates that are part of an animation we must wait for
3788 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003789 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003790 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003791 if (CC_UNLIKELY(err != NO_ERROR)) {
3792 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003793 // caller after a few seconds.
3794 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3795 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003796 mAnimTransactionPending = false;
3797 break;
3798 }
3799 }
3800 }
3801
chaviwca27f252018-02-06 16:46:39 -08003802 for (const DisplayState& display : displays) {
3803 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003804 }
3805
Marissa Walld600d572019-03-26 15:38:50 -07003806 // In case the client has sent a Transaction that should receive callbacks but without any
3807 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3808 // to the callback thread so it can send an empty callback
3809 if (!listenerCallbacks.empty()) {
3810 mTransactionCompletedThread.run();
3811 }
3812 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3813 mTransactionCompletedThread.addCallback(listener, callbackIds);
3814 }
3815
Marissa Walle2ffb422018-10-12 11:33:52 -07003816 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003817 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003818 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3819 postTime, privileged);
3820 }
3821
Marissa Walle2ffb422018-10-12 11:33:52 -07003822 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003823 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003824 mTransactionCompletedThread.sendCallbacks();
3825 }
3826 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003827
chaviw273171b2018-12-26 11:46:30 -08003828 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3829
Marissa Wall947d34e2019-03-29 14:03:53 -07003830 if (uncacheBuffer.isValid()) {
3831 ClientCache::getInstance().erase(uncacheBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003832 }
3833
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003834 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3835 // anyway. This can be used as a flush mechanism for previous async transactions.
3836 // Empty animation transaction can be used to simulate back-pressure, so also force a
3837 // transaction for empty animation transactions.
3838 if (transactionFlags == 0 &&
3839 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003840 transactionFlags = eTransactionNeeded;
3841 }
3842
Marissa Wall06255332019-03-27 13:48:27 -07003843 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3844 // so we don't have to wake up again next frame to preform an uneeded traversal.
3845 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3846 transactionFlags = transactionFlags & (~eTraversalNeeded);
3847 mTraversalNeededMainThread = true;
3848 }
3849
Mathias Agopian386aa982011-11-07 21:58:03 -08003850 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003851 if (mInterceptor->isEnabled()) {
3852 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003853 }
Irvel468051e2016-06-13 16:44:44 -07003854
Mathias Agopian386aa982011-11-07 21:58:03 -08003855 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003856 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3857 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003858 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003859
3860 // if this is a synchronous transaction, wait for it to take effect
3861 // before returning.
3862 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003863 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003864 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003865 if (flags & eAnimation) {
3866 mAnimTransactionPending = true;
3867 }
chaviw4fe36852019-04-15 16:25:49 -07003868 if (mPendingInputWindowCommands.syncInputWindows) {
3869 mPendingSyncInputWindows = true;
3870 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003871
3872 // applyTransactionState can be called by either the main SF thread or by
3873 // another process through setTransactionState. While a given process may wish
3874 // to wait on synchronous transactions, the main SF thread should never
3875 // be blocked. Therefore, we only wait if isMainThread is false.
3876 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003877 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3878 if (CC_UNLIKELY(err != NO_ERROR)) {
3879 // just in case something goes wrong in SF, return to the
3880 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003881 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3882 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003883 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003884 break;
3885 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003886 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887 }
3888}
3889
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003890uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3891 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3892 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003893
Mathias Agopiane57f2922012-08-09 16:29:12 -07003894 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003895 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3896
3897 const uint32_t what = s.what;
3898 if (what & DisplayState::eSurfaceChanged) {
3899 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3900 state.surface = s.surface;
3901 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003902 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003903 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003904 if (what & DisplayState::eLayerStackChanged) {
3905 if (state.layerStack != s.layerStack) {
3906 state.layerStack = s.layerStack;
3907 flags |= eDisplayTransactionNeeded;
3908 }
3909 }
3910 if (what & DisplayState::eDisplayProjectionChanged) {
3911 if (state.orientation != s.orientation) {
3912 state.orientation = s.orientation;
3913 flags |= eDisplayTransactionNeeded;
3914 }
3915 if (state.frame != s.frame) {
3916 state.frame = s.frame;
3917 flags |= eDisplayTransactionNeeded;
3918 }
3919 if (state.viewport != s.viewport) {
3920 state.viewport = s.viewport;
3921 flags |= eDisplayTransactionNeeded;
3922 }
3923 }
3924 if (what & DisplayState::eDisplaySizeChanged) {
3925 if (state.width != s.width) {
3926 state.width = s.width;
3927 flags |= eDisplayTransactionNeeded;
3928 }
3929 if (state.height != s.height) {
3930 state.height = s.height;
3931 flags |= eDisplayTransactionNeeded;
3932 }
3933 }
3934
Mathias Agopiane57f2922012-08-09 16:29:12 -07003935 return flags;
3936}
3937
Robert Carr14167e02019-02-13 13:50:55 -08003938bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003939 IPCThreadState* ipc = IPCThreadState::self();
3940 const int pid = ipc->getCallingPid();
3941 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003942 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003943 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003944 return false;
3945 }
3946 return true;
3947}
3948
Marissa Wall3dad52d2019-03-22 14:03:19 -07003949uint32_t SurfaceFlinger::setClientStateLocked(
3950 const ComposerState& composerState, int64_t desiredPresentTime,
3951 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3952 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003953 const layer_state_t& s = composerState.state;
3954 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3955
Mathias Agopian13127d82013-03-05 17:47:11 -08003956 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003957 if (layer == nullptr) {
3958 return 0;
3959 }
3960
chaviw8b3871a2017-11-01 17:41:01 -07003961 uint32_t flags = 0;
3962
Garfield Tan8a3083e2018-12-03 13:21:07 -08003963 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003964 bool geometryAppliesWithResize =
3965 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003966
3967 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3968 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003969 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003970 layer->pushPendingState();
3971 }
3972
chaviw8b3871a2017-11-01 17:41:01 -07003973 if (what & layer_state_t::ePositionChanged) {
3974 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3975 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003976 }
chaviw8b3871a2017-11-01 17:41:01 -07003977 }
3978 if (what & layer_state_t::eLayerChanged) {
3979 // NOTE: index needs to be calculated before we update the state
3980 const auto& p = layer->getParent();
3981 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003982 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003983 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003984 mCurrentState.layersSortedByZ.removeAt(idx);
3985 mCurrentState.layersSortedByZ.add(layer);
3986 // we need traversal (state changed)
3987 // AND transaction (list changed)
3988 flags |= eTransactionNeeded|eTraversalNeeded;
3989 }
chaviw8b3871a2017-11-01 17:41:01 -07003990 } else {
3991 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003992 flags |= eTransactionNeeded|eTraversalNeeded;
3993 }
3994 }
chaviw8b3871a2017-11-01 17:41:01 -07003995 }
3996 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003997 // NOTE: index needs to be calculated before we update the state
3998 const auto& p = layer->getParent();
3999 if (p == nullptr) {
4000 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4001 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4002 mCurrentState.layersSortedByZ.removeAt(idx);
4003 mCurrentState.layersSortedByZ.add(layer);
4004 // we need traversal (state changed)
4005 // AND transaction (list changed)
4006 flags |= eTransactionNeeded|eTraversalNeeded;
4007 }
4008 } else {
4009 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4010 flags |= eTransactionNeeded|eTraversalNeeded;
4011 }
chaviw8b3871a2017-11-01 17:41:01 -07004012 }
4013 }
4014 if (what & layer_state_t::eSizeChanged) {
4015 if (layer->setSize(s.w, s.h)) {
4016 flags |= eTraversalNeeded;
4017 }
4018 }
4019 if (what & layer_state_t::eAlphaChanged) {
4020 if (layer->setAlpha(s.alpha))
4021 flags |= eTraversalNeeded;
4022 }
4023 if (what & layer_state_t::eColorChanged) {
4024 if (layer->setColor(s.color))
4025 flags |= eTraversalNeeded;
4026 }
Peiyong Lind3788632018-09-18 16:01:31 -07004027 if (what & layer_state_t::eColorTransformChanged) {
4028 if (layer->setColorTransform(s.colorTransform)) {
4029 flags |= eTraversalNeeded;
4030 }
4031 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004032 if (what & layer_state_t::eBackgroundColorChanged) {
4033 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4034 flags |= eTraversalNeeded;
4035 }
4036 }
chaviw8b3871a2017-11-01 17:41:01 -07004037 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004038 // TODO: b/109894387
4039 //
4040 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4041 // rotation. To see the problem observe that if we have a square parent, and a child
4042 // of the same size, then we rotate the child 45 degrees around it's center, the child
4043 // must now be cropped to a non rectangular 8 sided region.
4044 //
4045 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4046 // private API, and the WindowManager only uses rotation in one case, which is on a top
4047 // level layer in which cropping is not an issue.
4048 //
4049 // However given that abuse of rotation matrices could lead to surfaces extending outside
4050 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4051 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4052 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004053 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004054 flags |= eTraversalNeeded;
4055 }
4056 if (what & layer_state_t::eTransparentRegionChanged) {
4057 if (layer->setTransparentRegionHint(s.transparentRegion))
4058 flags |= eTraversalNeeded;
4059 }
4060 if (what & layer_state_t::eFlagsChanged) {
4061 if (layer->setFlags(s.flags, s.mask))
4062 flags |= eTraversalNeeded;
4063 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004064 if (what & layer_state_t::eCropChanged_legacy) {
4065 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004066 flags |= eTraversalNeeded;
4067 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004068 if (what & layer_state_t::eCornerRadiusChanged) {
4069 if (layer->setCornerRadius(s.cornerRadius))
4070 flags |= eTraversalNeeded;
4071 }
chaviw8b3871a2017-11-01 17:41:01 -07004072 if (what & layer_state_t::eLayerStackChanged) {
4073 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4074 // We only allow setting layer stacks for top level layers,
4075 // everything else inherits layer stack from its parent.
4076 if (layer->hasParent()) {
4077 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4078 layer->getName().string());
4079 } else if (idx < 0) {
4080 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4081 "that also does not appear in the top level layer list. Something"
4082 " has gone wrong.", layer->getName().string());
4083 } else if (layer->setLayerStack(s.layerStack)) {
4084 mCurrentState.layersSortedByZ.removeAt(idx);
4085 mCurrentState.layersSortedByZ.add(layer);
4086 // we need traversal (state changed)
4087 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004088 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004089 }
4090 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004091 if (what & layer_state_t::eDeferTransaction_legacy) {
4092 if (s.barrierHandle_legacy != nullptr) {
4093 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4094 } else if (s.barrierGbp_legacy != nullptr) {
4095 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004096 if (authenticateSurfaceTextureLocked(gbp)) {
4097 const auto& otherLayer =
4098 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004099 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004100 } else {
4101 ALOGE("Attempt to defer transaction to to an"
4102 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004103 }
4104 }
chaviw8b3871a2017-11-01 17:41:01 -07004105 // We don't trigger a traversal here because if no other state is
4106 // changed, we don't want this to cause any more work
4107 }
4108 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004109 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004110 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004111 if (!hadParent) {
4112 mCurrentState.layersSortedByZ.remove(layer);
4113 }
chaviw8b3871a2017-11-01 17:41:01 -07004114 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004115 }
chaviw8b3871a2017-11-01 17:41:01 -07004116 }
4117 if (what & layer_state_t::eReparentChildren) {
4118 if (layer->reparentChildren(s.reparentHandle)) {
4119 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004120 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004121 }
chaviw8b3871a2017-11-01 17:41:01 -07004122 if (what & layer_state_t::eDetachChildren) {
4123 layer->detachChildren();
4124 }
4125 if (what & layer_state_t::eOverrideScalingModeChanged) {
4126 layer->setOverrideScalingMode(s.overrideScalingMode);
4127 // We don't trigger a traversal here because if no other state is
4128 // changed, we don't want this to cause any more work
4129 }
Marissa Wall61c58622018-07-18 10:12:20 -07004130 if (what & layer_state_t::eTransformChanged) {
4131 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4132 }
4133 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4134 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4135 flags |= eTraversalNeeded;
4136 }
4137 if (what & layer_state_t::eCropChanged) {
4138 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4139 }
Marissa Wall861616d2018-10-22 12:52:23 -07004140 if (what & layer_state_t::eFrameChanged) {
4141 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4142 }
Marissa Wall61c58622018-07-18 10:12:20 -07004143 if (what & layer_state_t::eAcquireFenceChanged) {
4144 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4145 }
4146 if (what & layer_state_t::eDataspaceChanged) {
4147 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4148 }
4149 if (what & layer_state_t::eHdrMetadataChanged) {
4150 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4151 }
4152 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4153 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4154 }
4155 if (what & layer_state_t::eApiChanged) {
4156 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4157 }
4158 if (what & layer_state_t::eSidebandStreamChanged) {
4159 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4160 }
Robert Carr720e5062018-07-30 17:45:14 -07004161 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004162 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004163 layer->setInputInfo(s.inputInfo);
4164 flags |= eTraversalNeeded;
4165 } else {
4166 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4167 }
Robert Carr720e5062018-07-30 17:45:14 -07004168 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004169 if (what & layer_state_t::eMetadataChanged) {
4170 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4171 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004172 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4173 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4174 flags |= eTraversalNeeded;
4175 }
4176 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004177 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004178 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004179 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004180 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4181 }
4182 }
Marissa Wall78b72202019-03-15 14:58:34 -07004183 bool bufferChanged = what & layer_state_t::eBufferChanged;
4184 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4185 sp<GraphicBuffer> buffer;
4186 if (bufferChanged && cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004187 ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
Alec Mouri0ff5e8c2019-06-01 18:51:35 -07004188 ClientCache::getInstance().registerErasedRecipient(s.cachedBuffer,
4189 wp<ClientCache::ErasedRecipient>(layer));
4190 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004191 buffer = s.buffer;
4192 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004193 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004194 } else if (bufferChanged) {
4195 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004196 }
Marissa Wall78b72202019-03-15 14:58:34 -07004197 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004198 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004199 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004200 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004201 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004202 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4203 // Do not put anything that updates layer state or modifies flags after
4204 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004205 return flags;
4206}
4207
chaviw273171b2018-12-26 11:46:30 -08004208uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4209 uint32_t flags = 0;
4210 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4211 flags |= eTraversalNeeded;
4212 }
4213
chaviwa911b102019-02-14 10:18:33 -08004214 if (inputWindowCommands.syncInputWindows) {
4215 flags |= eTraversalNeeded;
4216 }
4217
Vishnu Nairec0ab382019-02-13 15:32:56 -08004218 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004219 return flags;
4220}
4221
Marissa Wall2d814fb2019-04-09 18:52:57 +00004222status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4223 uint32_t h, PixelFormat format, uint32_t flags,
4224 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004225 sp<IGraphicBufferProducer>* gbp,
4226 const sp<IBinder>& parentHandle,
4227 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004228 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004229 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004230 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004231 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004232 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004233
Robert Carrc0df3122019-04-11 13:18:21 -07004234 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4235 "Expected only one of parentLayer or parentHandle to be non-null. "
4236 "Programmer error?");
4237
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004238 status_t result = NO_ERROR;
4239
4240 sp<Layer> layer;
4241
Cody Northropbc755282017-03-31 12:00:08 -06004242 String8 uniqueName = getUniqueLayerName(name);
4243
Evan Roskya1f1e152019-01-24 16:17:46 -08004244 bool primaryDisplayOnly = false;
4245
4246 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4247 // TODO b/64227542
4248 if (metadata.has(METADATA_WINDOW_TYPE)) {
4249 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4250 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004251 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004252 primaryDisplayOnly = true;
4253 }
4254 }
4255
Mathias Agopian3165cc22012-08-08 19:42:09 -07004256 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004257 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004258 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4259 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004260
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004261 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004262 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004263 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4264 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004265 break;
chaviw13fdc492017-06-27 12:40:18 -07004266 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004267 // check if buffer size is set for color layer.
4268 if (w > 0 || h > 0) {
4269 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4270 int(w), int(h));
4271 return BAD_VALUE;
4272 }
4273
Evan Roskya1f1e152019-01-24 16:17:46 -08004274 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4275 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004276 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004277 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004278 // check if buffer size is set for container layer.
4279 if (w > 0 || h > 0) {
4280 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4281 int(w), int(h));
4282 return BAD_VALUE;
4283 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004284 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4285 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004286 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004287 default:
4288 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004289 break;
4290 }
4291
Dan Stoza7d89d062015-04-30 13:29:25 -07004292 if (result != NO_ERROR) {
4293 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004294 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004295
Evan Roskya1f1e152019-01-24 16:17:46 -08004296 if (primaryDisplayOnly) {
4297 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004298 }
4299
Robert Carrb89ea9d2018-12-10 13:01:14 -08004300 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004301 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4302 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004303 if (result != NO_ERROR) {
4304 return result;
4305 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004306 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004307
4308 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004309 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004310}
4311
Cody Northropbc755282017-03-31 12:00:08 -06004312String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4313{
4314 bool matchFound = true;
4315 uint32_t dupeCounter = 0;
4316
4317 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4318 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4319
Dan Stoza436ccf32018-06-21 12:10:12 -07004320 // Grab the state lock since we're accessing mCurrentState
4321 Mutex::Autolock lock(mStateLock);
4322
Cody Northropbc755282017-03-31 12:00:08 -06004323 // Loop over layers until we're sure there is no matching name
4324 while (matchFound) {
4325 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004326 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004327 if (layer->getName() == uniqueName) {
4328 matchFound = true;
4329 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4330 }
4331 });
4332 }
4333
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004334 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4335 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004336
4337 return uniqueName;
4338}
4339
Marissa Wallfd668622018-05-10 10:21:13 -07004340status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4341 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004342 LayerMetadata metadata, PixelFormat& format,
4343 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004344 sp<IGraphicBufferProducer>* gbp,
4345 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004346 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004347 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004348 case PIXEL_FORMAT_TRANSPARENT:
4349 case PIXEL_FORMAT_TRANSLUCENT:
4350 format = PIXEL_FORMAT_RGBA_8888;
4351 break;
4352 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004353 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004354 break;
4355 }
4356
Evan Roskya1f1e152019-01-24 16:17:46 -08004357 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4358 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004359 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004360 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004361 *handle = layer->getHandle();
4362 *gbp = layer->getProducer();
4363 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004364 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004365
Marissa Wallfd668622018-05-10 10:21:13 -07004366 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004367 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004368}
4369
Marissa Wall61c58622018-07-18 10:12:20 -07004370status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4371 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004372 LayerMetadata metadata, sp<IBinder>* handle,
4373 sp<Layer>* outLayer) {
4374 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4375 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004376 *handle = layer->getHandle();
4377 *outLayer = layer;
4378
4379 return NO_ERROR;
4380}
4381
Evan Roskya1f1e152019-01-24 16:17:46 -08004382status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4383 uint32_t h, uint32_t flags, LayerMetadata metadata,
4384 sp<IBinder>* handle, sp<Layer>* outLayer) {
4385 *outLayer = getFactory().createColorLayer(
4386 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004387 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004388 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004389}
4390
Evan Roskya1f1e152019-01-24 16:17:46 -08004391status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4392 uint32_t w, uint32_t h, uint32_t flags,
4393 LayerMetadata metadata, sp<IBinder>* handle,
4394 sp<Layer>* outLayer) {
4395 *outLayer = getFactory().createContainerLayer(
4396 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004397 *handle = (*outLayer)->getHandle();
4398 return NO_ERROR;
4399}
4400
4401
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004402void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004403 mLayersPendingRemoval.add(layer);
4404 mLayersRemoved = true;
4405 setTransactionFlags(eTransactionNeeded);
4406}
4407
Robert Carr695d5282018-12-18 15:27:58 -08004408void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004409{
Robert Carr2e102c92018-10-23 12:11:15 -07004410 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004411 // If a layer has a parent, we allow it to out-live it's handle
4412 // with the idea that the parent holds a reference and will eventually
4413 // be cleaned up. However no one cleans up the top-level so we do so
4414 // here.
4415 if (layer->getParent() == nullptr) {
4416 mCurrentState.layersSortedByZ.remove(layer);
4417 }
4418 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004419
4420 auto it = mLayersByLocalBinderToken.begin();
4421 while (it != mLayersByLocalBinderToken.end()) {
4422 if (it->second == layer) {
4423 it = mLayersByLocalBinderToken.erase(it);
4424 } else {
4425 it++;
4426 }
4427 }
4428
Robert Carr695d5282018-12-18 15:27:58 -08004429 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004430}
4431
Mathias Agopianb60314a2012-04-10 22:09:54 -07004432// ---------------------------------------------------------------------------
4433
Andy McFadden13a082e2012-08-24 10:16:42 -07004434void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004435 const auto display = getDefaultDisplayDeviceLocked();
4436 if (!display) return;
4437
4438 const sp<IBinder> token = display->getDisplayToken().promote();
4439 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004440
Jesse Hall01e29052013-02-19 16:13:35 -08004441 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004442 Vector<ComposerState> state;
4443 Vector<DisplayState> displays;
4444 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004445 d.what = DisplayState::eDisplayProjectionChanged |
4446 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004447 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004448 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004449 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004450 d.frame.makeInvalid();
4451 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004452 d.width = 0;
4453 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004454 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004455 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004456
Dominik Laskowskie9774092018-12-11 10:04:24 -08004457 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004458
Dominik Laskowski83b88212018-12-11 13:34:06 -08004459 const nsecs_t vsyncPeriod = getVsyncPeriod();
4460 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004461
Brian Andersond0010582017-03-07 13:20:31 -08004462 // Use phase of 0 since phase is not known.
4463 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004464 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004465 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004466}
4467
4468void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004469 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004470 postMessageAsync(
4471 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004472}
4473
Ady Abrahamb0006972019-06-11 10:52:26 -07004474void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4475 if (mHWCVsyncState != enabled) {
4476 getHwComposer().setVsyncEnabled(displayId, enabled);
4477 mHWCVsyncState = enabled;
4478 }
4479}
4480
Dominik Laskowskie9774092018-12-11 10:04:24 -08004481void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004482 if (display->isVirtual()) {
4483 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004484 return;
4485 }
4486
Dominik Laskowski075d3172018-05-24 15:50:06 -07004487 const auto displayId = display->getId();
4488 LOG_ALWAYS_FATAL_IF(!displayId);
4489
Dominik Laskowski34157762018-10-31 13:07:19 -07004490 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004491
4492 int currentMode = display->getPowerMode();
4493 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004494 return;
4495 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004496
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004497 display->setPowerMode(mode);
4498
Lloyd Pique4dccc412018-01-22 17:21:36 -08004499 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004500 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004501 }
4502
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004503 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004504 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004505 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004506 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abrahamb0006972019-06-11 10:52:26 -07004507 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004508 mScheduler->onScreenAcquired(mAppConnectionHandle);
4509 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004511
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004512 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004513 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004514 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004515
4516 struct sched_param param = {0};
4517 param.sched_priority = 1;
4518 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4519 ALOGW("Couldn't set SCHED_FIFO on display on");
4520 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004521 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004522 // Turn off the display
4523 struct sched_param param = {0};
4524 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4525 ALOGW("Couldn't set SCHED_OTHER on display off");
4526 }
4527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004528 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004529 mScheduler->disableHardwareVsync(true);
4530 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004531 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004532
Ady Abrahamb0006972019-06-11 10:52:26 -07004533 // Make sure HWVsync is disabled before turning off the display
4534 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4535
Dominik Laskowski075d3172018-05-24 15:50:06 -07004536 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004537 mVisibleRegionsDirty = true;
4538 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004539 } else if (mode == HWC_POWER_MODE_DOZE ||
4540 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004541 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004542 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004543 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004544 mScheduler->onScreenAcquired(mAppConnectionHandle);
4545 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004546 }
4547 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4548 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004549 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004550 mScheduler->disableHardwareVsync(true);
4551 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004552 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004553 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004554 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004555 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004556 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004557 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004558
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004559 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004560 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004561 mRefreshRateStats.setPowerMode(mode);
Ady Abrahama133f032019-07-12 12:37:57 -07004562 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004563 }
4564
Dominik Laskowski34157762018-10-31 13:07:19 -07004565 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004566}
4567
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004568void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004569 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004570 const auto display = getDisplayDevice(displayToken);
4571 if (!display) {
4572 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4573 displayToken.get());
4574 } else if (display->isVirtual()) {
4575 ALOGW("Attempt to set power mode %d for virtual display", mode);
4576 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004577 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004578 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004579 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004580}
4581
4582// ---------------------------------------------------------------------------
4583
Dominik Laskowskic2867142019-01-21 11:33:38 -08004584status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4585 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004586 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004587
Mathias Agopianbd115332013-04-18 16:41:04 -07004588 IPCThreadState* ipc = IPCThreadState::self();
4589 const int pid = ipc->getCallingPid();
4590 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004591
Mathias Agopianbd115332013-04-18 16:41:04 -07004592 if ((uid != AID_SHELL) &&
4593 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4595 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004596 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004597 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004598 // (this would indicate SF is stuck, but we want to be able to
4599 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004600 status_t err = mStateLock.timedLock(s2ns(1));
4601 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004602 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004603 StringAppendF(&result,
4604 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4605 "(no locks held)\n",
4606 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004607 }
4608
Dominik Laskowskic2867142019-01-21 11:33:38 -08004609 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004610
Dominik Laskowskic2867142019-01-21 11:33:38 -08004611 static const std::unordered_map<std::string, Dumper> dumpers = {
4612 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4613 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4614 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004615 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004616 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004617 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004618 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4619 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004620 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4621 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4622 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4623 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4624 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4625 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004626 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004627 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4628 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004629
Dominik Laskowskic2867142019-01-21 11:33:38 -08004630 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004631
Dominik Laskowskic2867142019-01-21 11:33:38 -08004632 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4633 (it->second)(args, asProto, result);
4634 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004635 if (asProto) {
4636 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4637 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4638 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004639 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004640 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004641 }
4642
Mathias Agopian9795c422009-08-26 16:36:26 -07004643 if (locked) {
4644 mStateLock.unlock();
4645 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004646 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004648 return NO_ERROR;
4649}
4650
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004651status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4652 if (asProto && mTracing.isEnabled()) {
4653 mTracing.writeToFileAsync();
4654 }
4655
4656 return doDump(fd, DumpArgs(), asProto);
4657}
4658
Dominik Laskowskic2867142019-01-21 11:33:38 -08004659void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 mCurrentState.traverseInZOrder(
4661 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004662}
4663
Dominik Laskowskic2867142019-01-21 11:33:38 -08004664void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004665 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004666
Dominik Laskowskic2867142019-01-21 11:33:38 -08004667 if (args.size() > 1) {
4668 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004669 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004670 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004671 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004672 }
Robert Carr2047fae2016-11-28 14:09:09 -08004673 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004674 } else {
4675 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676 }
4677}
4678
Dominik Laskowskic2867142019-01-21 11:33:38 -08004679void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004680 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004681 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004682 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004683 }
Robert Carr2047fae2016-11-28 14:09:09 -08004684 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004685
Svetoslavd85084b2014-03-20 10:28:31 -07004686 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004687}
4688
Dominik Laskowskic2867142019-01-21 11:33:38 -08004689void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4690 mTimeStats->parseArgs(asProto, args, result);
4691}
4692
Jamie Gennis6547ff42013-07-16 20:12:42 -07004693// This should only be called from the main thread. Otherwise it would need
4694// the lock and should use mCurrentState rather than mDrawingState.
4695void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004696 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004697 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004698 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004699
4700 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4701}
4702
Yiwei Zhang5434a782018-12-05 18:06:32 -08004703void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004704 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004705
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004706 if (isLayerTripleBufferingDisabled())
4707 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004708
Yiwei Zhang5434a782018-12-05 18:06:32 -08004709 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4710 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4711 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4712 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4713 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4714 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004715 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004716}
4717
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004718void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004719 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004720 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004721 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004722 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004723
Ady Abraham97d04232019-03-05 19:48:12 -08004724 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004725 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4726 mUseSmart90ForVideo ? "on" : "off");
Ady Abrahamd4043c82019-07-09 18:09:52 -07004727 StringAppendF(&result, "Allowed Display Configs: ");
4728 for (int32_t configId : mAllowedDisplayConfigs) {
4729 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4730 if (refresh.second && refresh.second->configId == configId) {
4731 StringAppendF(&result, "%dHz, ", refresh.second->fps);
4732 }
4733 }
4734 }
4735 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4736 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004737 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004738}
4739
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4741 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004742 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4743 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004744 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004745 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004746 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004747 }
David Sodman4a36e932017-11-07 14:29:47 -08004748 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004749 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004750 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4752 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004753}
4754
Dan Stozae77c7662016-05-13 11:37:28 -07004755void SurfaceFlinger::recordBufferingStats(const char* layerName,
4756 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004757 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4758 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004759 for (const auto& segment : history) {
4760 if (!segment.usedThirdBuffer) {
4761 stats.twoBufferTime += segment.totalTime;
4762 }
4763 if (segment.occupancyAverage < 1.0f) {
4764 stats.doubleBufferedTime += segment.totalTime;
4765 } else if (segment.occupancyAverage < 2.0f) {
4766 stats.tripleBufferedTime += segment.totalTime;
4767 }
4768 ++stats.numSegments;
4769 stats.totalTime += segment.totalTime;
4770 }
4771}
4772
Yiwei Zhang5434a782018-12-05 18:06:32 -08004773void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4774 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004775
4776 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4777 const size_t count = currentLayers.size();
4778 for (size_t i=0 ; i<count ; i++) {
4779 currentLayers[i]->dumpFrameEvents(result);
4780 }
4781}
4782
Yiwei Zhang5434a782018-12-05 18:06:32 -08004783void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004784 result.append("Buffering stats:\n");
4785 result.append(" [Layer name] <Active time> <Two buffer> "
4786 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004787 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004788 typedef std::tuple<std::string, float, float, float> BufferTuple;
4789 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004790 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004791 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004792 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004793 if (stats.numSegments == 0) {
4794 continue;
4795 }
4796 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4797 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4798 stats.totalTime;
4799 float doubleBufferRatio = static_cast<float>(
4800 stats.doubleBufferedTime) / stats.totalTime;
4801 float tripleBufferRatio = static_cast<float>(
4802 stats.tripleBufferedTime) / stats.totalTime;
4803 sorted.insert({activeTime, {name, twoBufferRatio,
4804 doubleBufferRatio, tripleBufferRatio}});
4805 }
4806 for (const auto& sortedPair : sorted) {
4807 float activeTime = sortedPair.first;
4808 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004809 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4810 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004811 }
4812 result.append("\n");
4813}
4814
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004816 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004817 const auto displayId = display->getId();
4818 if (!displayId) {
4819 continue;
4820 }
4821 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004822 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004823 continue;
4824 }
4825
Yiwei Zhang5434a782018-12-05 18:06:32 -08004826 StringAppendF(&result,
4827 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4828 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004829 uint8_t port;
4830 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004831 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004832 result.append("no identification data\n");
4833 continue;
4834 }
4835
4836 if (!isEdid(data)) {
4837 result.append("unknown identification data: ");
4838 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004839 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004840 }
4841 result.append("\n");
4842 continue;
4843 }
4844
4845 const auto edid = parseEdid(data);
4846 if (!edid) {
4847 result.append("invalid EDID: ");
4848 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004849 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004850 }
4851 result.append("\n");
4852 continue;
4853 }
4854
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004856 result.append(edid->displayName.data(), edid->displayName.length());
4857 result.append("\"\n");
4858 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004859}
4860
Yiwei Zhang5434a782018-12-05 18:06:32 -08004861void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004862 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004863 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4864 StringAppendF(&result, "DisplayColorSetting: %s\n",
4865 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004866
4867 // TODO: print out if wide-color mode is active or not
4868
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004869 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004870 const auto displayId = display->getId();
4871 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004872 continue;
4873 }
4874
Yiwei Zhang5434a782018-12-05 18:06:32 -08004875 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004876 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004877 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004878 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004879 }
4880
Lloyd Pique32cbe282018-10-19 13:09:22 -07004881 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004882 StringAppendF(&result, " Current color mode: %s (%d)\n",
4883 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004884 }
4885 result.append("\n");
4886}
4887
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004888LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4889 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004890 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004891 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4892 const State& state = useDrawing ? mDrawingState : mCurrentState;
4893 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004894 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004895 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004896 });
4897
4898 return layersProto;
4899}
4900
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004901LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4902 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004903 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004904
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004905 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004906 resolution->set_w(displayDevice->getWidth());
4907 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004908
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004909 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004910 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004911
Lloyd Pique32cbe282018-10-19 13:09:22 -07004912 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4913 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4914 layersProto.set_global_transform(displayState.orientation);
4915
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004916 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004917 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004918 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004919 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004920 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004921 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004922 }
4923 });
4924
4925 return layersProto;
4926}
4927
Dominik Laskowskic2867142019-01-21 11:33:38 -08004928void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4929 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004930 Colorizer colorizer(colorize);
4931
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004932 // figure out if we're stuck somewhere
4933 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004934 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004935 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4936
4937 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004938 * Dump library configuration.
4939 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004940
4941 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004942 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004943 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004944 appendSfConfigString(result);
4945 appendUiConfigString(result);
4946 appendGuiConfigString(result);
4947 result.append("\n");
4948
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004949 result.append("\nDisplay identification data:\n");
4950 dumpDisplayIdentificationData(result);
4951
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004952 result.append("\nWide-Color information:\n");
4953 dumpWideColorInfo(result);
4954
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004955 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004956 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004957 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004958 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004959 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004960
Andy McFadden41d67d72014-04-25 16:58:34 -07004961 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004962 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004963 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004964 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004965 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004966
Dan Stozab90cf072015-03-05 11:05:59 -08004967 dumpStaticScreenStats(result);
4968 result.append("\n");
4969
Alec Mouri40189b02019-03-05 15:07:54 -08004970 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4971 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4972 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004973
Dan Stozae77c7662016-05-13 11:37:28 -07004974 dumpBufferingStats(result);
4975
Andy McFadden4803b742012-09-24 19:07:20 -07004976 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004977 * Dump the visible layer list
4978 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004979 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004980 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4981 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4982 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004983 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004984
Chia-I Wu2f884132018-09-13 15:17:58 -07004985 {
4986 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4987 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004988 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004989 result.append("\n");
4990 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004991
Lloyd Pique207def92019-02-28 16:09:52 -08004992 {
4993 StringAppendF(&result, "Composition layers\n");
4994 mDrawingState.traverseInZOrder([&](Layer* layer) {
4995 auto compositionLayer = layer->getCompositionLayer();
4996 if (compositionLayer) compositionLayer->dump(result);
4997 });
4998 }
4999
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005000 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005001 * Dump Display state
5002 */
5003
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005004 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005005 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005006 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005007 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005008 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005009 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005010 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005011
5012 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005013 * Dump SurfaceFlinger global state
5014 */
5015
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005016 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005017 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005018 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005019
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005020 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005021
Dominik Laskowski075d3172018-05-24 15:50:06 -07005022 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005023 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5024 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005025 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5026 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005027 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005028 StringAppendF(&result,
5029 " transaction-flags : %08x\n"
5030 " gpu_to_cpu_unsupported : %d\n",
5031 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005032
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005033 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005034 displayId && getHwComposer().isConnected(*displayId)) {
5035 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005036 StringAppendF(&result,
5037 " refresh-rate : %f fps\n"
5038 " x-dpi : %f\n"
5039 " y-dpi : %f\n",
5040 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5041 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005042 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005043
Yiwei Zhang5434a782018-12-05 18:06:32 -08005044 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005045
Dan Stozae22aec72016-08-01 13:20:59 -07005046 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005047 * Tracing state
5048 */
5049 mTracing.dump(result);
5050 result.append("\n");
5051
5052 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005053 * HWC layer minidump
5054 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005055 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005056 const auto displayId = display->getId();
5057 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005058 continue;
5059 }
5060
Yiwei Zhang5434a782018-12-05 18:06:32 -08005061 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005062 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005063 const sp<DisplayDevice> displayDevice = display;
5064 mCurrentState.traverseInZOrder(
5065 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005066 result.append("\n");
5067 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005068
5069 /*
5070 * Dump HWComposer state
5071 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005072 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005073 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005074 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005075 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005076 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005077 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005078
5079 /*
5080 * Dump gralloc state
5081 */
5082 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5083 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005084
5085 /*
5086 * Dump VrFlinger state if in use.
5087 */
5088 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5089 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005090 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005091 result.append("\n");
5092 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005093
5094 /**
5095 * Scheduler dump state.
5096 */
Ana Krulecc2870422019-01-29 19:00:58 -08005097 result.append("\nScheduler state:\n");
5098 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005099 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005100 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005101
5102 result.append(mTimeStats->miniDump());
5103 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005104}
5105
Dominik Laskowski075d3172018-05-24 15:50:06 -07005106const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005107 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005108 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005109 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005110 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005111 }
5112 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005113
Dominik Laskowski34157762018-10-31 13:07:19 -07005114 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005115 static const Vector<sp<Layer>> empty;
5116 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005117}
5118
Chia-I Wu28f320b2018-05-03 11:02:56 -07005119void SurfaceFlinger::updateColorMatrixLocked() {
5120 mat4 colorMatrix;
5121 if (mGlobalSaturationFactor != 1.0f) {
5122 // Rec.709 luma coefficients
5123 float3 luminance{0.213f, 0.715f, 0.072f};
5124 luminance *= 1.0f - mGlobalSaturationFactor;
5125 mat4 saturationMatrix = mat4(
5126 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5127 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5128 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5129 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5130 );
5131 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5132 } else {
5133 colorMatrix = mClientColorMatrix * mDaltonizer();
5134 }
5135
5136 if (mCurrentState.colorMatrix != colorMatrix) {
5137 mCurrentState.colorMatrix = colorMatrix;
5138 mCurrentState.colorMatrixChanged = true;
5139 setTransactionFlags(eTransactionNeeded);
5140 }
5141}
5142
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005143status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005144#pragma clang diagnostic push
5145#pragma clang diagnostic error "-Wswitch-enum"
5146 switch (static_cast<ISurfaceComposerTag>(code)) {
5147 // These methods should at minimum make sure that the client requested
5148 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005149 case BOOT_FINISHED:
5150 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005151 case CREATE_DISPLAY:
5152 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005153 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005154 case GET_ANIMATION_FRAME_STATS:
5155 case GET_HDR_CAPABILITIES:
5156 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005157 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005158 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005159 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005160 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005161 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005162 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005163 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005164 case GET_DISPLAYED_CONTENT_SAMPLE:
5165 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005166 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5167 IPCThreadState* ipc = IPCThreadState::self();
5168 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5169 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005170 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005171 }
Robert Carr1db73f62016-12-21 12:58:51 -08005172 return OK;
5173 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005174 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005175 IPCThreadState* ipc = IPCThreadState::self();
5176 const int pid = ipc->getCallingPid();
5177 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005178 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5179 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005180 return PERMISSION_DENIED;
5181 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005182 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005183 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005184 // Used by apps to hook Choreographer to SurfaceFlinger.
5185 case CREATE_DISPLAY_EVENT_CONNECTION:
5186 // The following calls are currently used by clients that do not
5187 // request necessary permissions. However, they do not expose any secret
5188 // information, so it is OK to pass them.
5189 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005190 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005191 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005192 case GET_PHYSICAL_DISPLAY_IDS:
5193 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005194 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005195 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005196 case GET_DISPLAY_CONFIGS:
5197 case GET_DISPLAY_STATS:
5198 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5199 // Calling setTransactionState is safe, because you need to have been
5200 // granted a reference to Client* and Handle* to do anything with it.
5201 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005202 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005203 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005204 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005205 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005206 case IS_WIDE_COLOR_DISPLAY:
5207 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5208 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005209 return OK;
5210 }
5211 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005212 case CAPTURE_SCREEN:
5213 case ADD_REGION_SAMPLING_LISTENER:
5214 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005215 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005216 IPCThreadState* ipc = IPCThreadState::self();
5217 const int pid = ipc->getCallingPid();
5218 const int uid = ipc->getCallingUid();
5219 if ((uid != AID_GRAPHICS) &&
5220 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5221 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5222 return PERMISSION_DENIED;
5223 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005224 return OK;
5225 }
5226 // The following codes are deprecated and should never be allowed to access SF.
5227 case CONNECT_DISPLAY_UNUSED:
5228 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5229 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5230 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005231 }
chaviw93df2ea2019-04-30 16:45:12 -07005232 case CAPTURE_SCREEN_BY_ID: {
5233 IPCThreadState* ipc = IPCThreadState::self();
5234 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005235 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005236 return OK;
5237 }
5238 return PERMISSION_DENIED;
5239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005240 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005241
5242 // These codes are used for the IBinder protocol to either interrogate the recipient
5243 // side of the transaction for its canonical interface descriptor or to dump its state.
5244 // We let them pass by default.
5245 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5246 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5247 code == IBinder::SYSPROPS_TRANSACTION) {
5248 return OK;
5249 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005250 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005251 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005252 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005253 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5254 return OK;
5255 }
5256 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5257 return PERMISSION_DENIED;
5258#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005259}
5260
Ana Krulec13be8ad2018-08-21 02:43:56 +00005261status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5262 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005263 status_t credentialCheck = CheckTransactCodeCredentials(code);
5264 if (credentialCheck != OK) {
5265 return credentialCheck;
5266 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005267
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005268 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5269 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005270 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005271 IPCThreadState* ipc = IPCThreadState::self();
5272 const int uid = ipc->getCallingUid();
5273 if (CC_UNLIKELY(uid != AID_SYSTEM
5274 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005275 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005276 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005277 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005278 return PERMISSION_DENIED;
5279 }
5280 int n;
5281 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005282 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005283 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005284 return NO_ERROR;
5285 case 1002: // SHOW_UPDATES
5286 n = data.readInt32();
5287 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005288 invalidateHwcGeometry();
5289 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005290 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005291 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005292 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005293 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005294 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005295 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005296 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005297 setTransactionFlags(
5298 eTransactionNeeded|
5299 eDisplayTransactionNeeded|
5300 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005301 return NO_ERROR;
5302 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005303 case 1006:{ // send empty update
5304 signalRefresh();
5305 return NO_ERROR;
5306 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005307 case 1008: // toggle use of hw composer
5308 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005309 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005310 invalidateHwcGeometry();
5311 repaintEverything();
5312 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005313 case 1009: // toggle use of transform hint
5314 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005315 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005316 invalidateHwcGeometry();
5317 repaintEverything();
5318 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005319 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005320 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005321 reply->writeInt32(0);
5322 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005323 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005324 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005325 return NO_ERROR;
5326 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005327 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005328 if (!display) {
5329 return NAME_NOT_FOUND;
5330 }
5331
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005332 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005333 return NO_ERROR;
5334 }
5335 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005336 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005337 // daltonize
5338 n = data.readInt32();
5339 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005340 case 1:
5341 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5342 break;
5343 case 2:
5344 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5345 break;
5346 case 3:
5347 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5348 break;
5349 default:
5350 mDaltonizer.setType(ColorBlindnessType::None);
5351 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005352 }
5353 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005354 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005355 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005356 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005357 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005358
5359 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005360 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005361 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005362 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005363 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005364 // apply a color matrix
5365 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005366 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005367 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005368 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005369 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005370 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005371 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005372 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005373 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005374 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005375 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005376
5377 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5378 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005379 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005380 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5381 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5382 }
5383
Chia-I Wu28f320b2018-05-03 11:02:56 -07005384 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005385 return NO_ERROR;
5386 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005387 // This is an experimental interface
5388 // Needs to be shifted to proper binder interface when we productize
5389 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005390 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005391 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005392 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005393 return NO_ERROR;
5394 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005395 case 1017: {
5396 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005397 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005398 return NO_ERROR;
5399 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005400 case 1018: { // Modify Choreographer's phase offset
5401 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005402 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005403 return NO_ERROR;
5404 }
5405 case 1019: { // Modify SurfaceFlinger's phase offset
5406 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005407 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005408 return NO_ERROR;
5409 }
Irvel468051e2016-06-13 16:44:44 -07005410 case 1020: { // Layer updates interceptor
5411 n = data.readInt32();
5412 if (n) {
5413 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005414 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005415 }
5416 else{
5417 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005418 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005419 }
5420 return NO_ERROR;
5421 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005422 case 1021: { // Disable HWC virtual displays
5423 n = data.readInt32();
5424 mUseHwcVirtualDisplays = !n;
5425 return NO_ERROR;
5426 }
Romain Guy0147a172017-06-01 13:53:56 -07005427 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005428 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005429 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005430
Chia-I Wu28f320b2018-05-03 11:02:56 -07005431 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005432 return NO_ERROR;
5433 }
Romain Guy54f154a2017-10-24 21:40:32 +01005434 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005435 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005436 invalidateHwcGeometry();
5437 repaintEverything();
5438 return NO_ERROR;
5439 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005440 // Deprecate, use 1030 to check whether the device is color managed.
5441 case 1024: {
5442 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005443 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005444 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005445 n = data.readInt32();
5446 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005447 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005448 Mutex::Autolock lock(mStateLock);
5449 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005450 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005451 reply->writeInt32(NO_ERROR);
5452 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005453 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005454 bool writeFile = false;
5455 {
5456 Mutex::Autolock lock(mStateLock);
5457 mTracingEnabledChanged = true;
5458 writeFile = mTracing.disable();
5459 }
5460
5461 if (writeFile) {
5462 reply->writeInt32(mTracing.writeToFile());
5463 } else {
5464 reply->writeInt32(NO_ERROR);
5465 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005466 }
5467 return NO_ERROR;
5468 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005469 case 1026: { // Get layer tracing status
5470 reply->writeBool(mTracing.isEnabled());
5471 return NO_ERROR;
5472 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005473 // Is a DisplayColorSetting supported?
5474 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005475 const auto display = getDefaultDisplayDevice();
5476 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005477 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005478 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005479
5480 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5481 switch (setting) {
5482 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005483 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005484 break;
5485 case DisplayColorSetting::UNMANAGED:
5486 reply->writeBool(true);
5487 break;
5488 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005489 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005490 break;
5491 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005492 reply->writeBool(
5493 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005494 break;
5495 }
5496 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005497 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005498 // Is VrFlinger active?
5499 case 1028: {
5500 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005501 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005502 return NO_ERROR;
5503 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005504 // Set buffer size for SF tracing (value in KB)
5505 case 1029: {
5506 n = data.readInt32();
5507 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5508 ALOGW("Invalid buffer size: %d KB", n);
5509 reply->writeInt32(BAD_VALUE);
5510 return BAD_VALUE;
5511 }
5512
5513 ALOGD("Updating trace buffer to %d KB", n);
5514 mTracing.setBufferSize(n * 1024);
5515 reply->writeInt32(NO_ERROR);
5516 return NO_ERROR;
5517 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005518 // Is device color managed?
5519 case 1030: {
5520 reply->writeBool(useColorManagement);
5521 return NO_ERROR;
5522 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005523 // Override default composition data space
5524 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5525 // && adb shell stop zygote && adb shell start zygote
5526 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5527 // adb shell stop zygote && adb shell start zygote
5528 case 1031: {
5529 Mutex::Autolock _l(mStateLock);
5530 n = data.readInt32();
5531 if (n) {
5532 n = data.readInt32();
5533 if (n) {
5534 Dataspace dataspace = static_cast<Dataspace>(n);
5535 if (!validateCompositionDataspace(dataspace)) {
5536 return BAD_VALUE;
5537 }
5538 mDefaultCompositionDataspace = dataspace;
5539 }
5540 n = data.readInt32();
5541 if (n) {
5542 Dataspace dataspace = static_cast<Dataspace>(n);
5543 if (!validateCompositionDataspace(dataspace)) {
5544 return BAD_VALUE;
5545 }
5546 mWideColorGamutCompositionDataspace = dataspace;
5547 }
5548 } else {
5549 // restore composition data space.
5550 mDefaultCompositionDataspace = defaultCompositionDataspace;
5551 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5552 }
5553 return NO_ERROR;
5554 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005555 // Set trace flags
5556 case 1033: {
5557 n = data.readUint32();
5558 ALOGD("Updating trace flags to 0x%x", n);
5559 mTracing.setTraceFlags(n);
5560 reply->writeInt32(NO_ERROR);
5561 return NO_ERROR;
5562 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005563 case 1034: {
5564 // TODO(b/129297325): expose this via developer menu option
5565 n = data.readInt32();
5566 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005567 RefreshRateType type;
5568 {
5569 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5570 type = mDesiredActiveConfig.type;
5571 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005572 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005573 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005574 } else if (!n) {
5575 mRefreshRateOverlay.reset();
5576 }
5577 return NO_ERROR;
5578 }
Ady Abraham34392f72019-04-10 11:29:27 -07005579 case 1035: {
5580 n = data.readInt32();
5581 mDebugDisplayConfigSetByBackdoor = false;
5582 if (n >= 0) {
5583 const auto displayToken = getInternalDisplayToken();
5584 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5585 if (result != NO_ERROR) {
5586 return result;
5587 }
5588 mDebugDisplayConfigSetByBackdoor = true;
5589 }
5590 return NO_ERROR;
5591 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005592 }
5593 }
5594 return err;
5595}
5596
Steven Thomas6d8110b2017-08-31 18:24:21 -07005597void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005598 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005599 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005600}
5601
Ana Krulec7d1d6832018-12-27 11:10:09 -08005602void SurfaceFlinger::repaintEverythingForHWC() {
5603 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005604 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005605}
5606
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005607// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5608class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005609public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005610 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5611 ~WindowDisconnector() {
5612 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005613 }
5614
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005615private:
5616 ANativeWindow* mWindow;
5617 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005618};
5619
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005620status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005621 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5622 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005623 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005624 uint32_t reqWidth, uint32_t reqHeight,
5625 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005626 ISurfaceComposer::Rotation rotation,
5627 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005629
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005630 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005631
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005632 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5633
Chia-I Wu20261cb2018-08-23 12:55:44 -07005634 sp<DisplayDevice> display;
5635 {
5636 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005637
Chia-I Wu20261cb2018-08-23 12:55:44 -07005638 display = getDisplayDeviceLocked(displayToken);
5639 if (!display) return BAD_VALUE;
5640
Chia-I Wucb023152018-08-28 12:57:23 -07005641 // set the requested width/height to the logical display viewport size
5642 // by default
5643 if (reqWidth == 0 || reqHeight == 0) {
5644 reqWidth = uint32_t(display->getViewport().width());
5645 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005646 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005647 }
5648
Peiyong Lin0e003c92018-09-17 11:09:51 -07005649 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005650 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005651
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005652 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5653 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005654 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005655 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005656}
5657
chaviw93df2ea2019-04-30 16:45:12 -07005658static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5659 switch (colorMode) {
5660 case ColorMode::DISPLAY_P3:
5661 case ColorMode::BT2100_PQ:
5662 case ColorMode::BT2100_HLG:
5663 case ColorMode::DISPLAY_BT2020:
5664 return Dataspace::DISPLAY_P3;
5665 default:
5666 return Dataspace::V0_SRGB;
5667 }
5668}
5669
5670const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5671 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5672 if (displayToken) {
5673 return getDisplayDeviceLocked(displayToken);
5674 }
5675 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5676 // may not have a displayId.
5677 for (const auto& [token, display] : mDisplays) {
5678 if (display->getLayerStack() == displayOrLayerStack) {
5679 return display;
5680 }
5681 }
5682 return nullptr;
5683}
5684
5685status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5686 sp<GraphicBuffer>* outBuffer) {
5687 sp<DisplayDevice> display;
5688 uint32_t width;
5689 uint32_t height;
5690 ui::Transform::orientation_flags captureOrientation;
5691 {
5692 Mutex::Autolock _l(mStateLock);
5693 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5694 if (!display) {
5695 return BAD_VALUE;
5696 }
5697
5698 width = uint32_t(display->getViewport().width());
5699 height = uint32_t(display->getViewport().height());
5700
5701 captureOrientation = fromSurfaceComposerRotation(
5702 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005703 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5704 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5705 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5706 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5707 }
chaviw93df2ea2019-04-30 16:45:12 -07005708 *outDataspace =
5709 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5710 }
5711
5712 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5713 false /* captureSecureLayers */);
5714
5715 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5716 std::placeholders::_1);
5717 bool ignored = false;
5718 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5719 false /* useIdentityTransform */,
5720 ignored /* outCapturedSecureLayers */);
5721}
5722
Robert Carr866455f2019-04-02 16:28:26 -07005723status_t SurfaceFlinger::captureLayers(
5724 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5725 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5726 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5727 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005728 ATRACE_CALL();
5729
5730 class LayerRenderArea : public RenderArea {
5731 public:
Robert Carr578038f2018-03-09 12:25:24 -08005732 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005733 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5734 bool childrenOnly)
5735 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005736 mLayer(layer),
5737 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005738 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005739 mFlinger(flinger),
5740 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005741 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005742 Rect getBounds() const override {
5743 const Layer::State& layerState(mLayer->getDrawingState());
5744 return mLayer->getBufferSize(layerState);
5745 }
Marissa Wall61c58622018-07-18 10:12:20 -07005746 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005747 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005748 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005749 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005750 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005751 }
chaviwa76b2712017-09-20 12:02:26 -07005752 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005753 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005754 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005755 Rect getSourceCrop() const override {
5756 if (mCrop.isEmpty()) {
5757 return getBounds();
5758 } else {
5759 return mCrop;
5760 }
5761 }
Robert Carr578038f2018-03-09 12:25:24 -08005762 class ReparentForDrawing {
5763 public:
5764 const sp<Layer>& oldParent;
5765 const sp<Layer>& newParent;
5766
Vishnu Nair4351ad52019-02-11 14:13:02 -08005767 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5768 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005769 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005770 // Compute and cache the bounds for the new parent layer.
5771 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005772 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005773 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005774 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005775 };
5776
5777 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005778 const Rect sourceCrop = getSourceCrop();
5779 // no need to check rotation because there is none
5780 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5781 sourceCrop.height() != getReqHeight();
5782
Robert Carr578038f2018-03-09 12:25:24 -08005783 if (!mChildrenOnly) {
5784 mTransform = mLayer->getTransform().inverse();
5785 drawLayers();
5786 } else {
5787 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005788 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005789 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005790 bounds.getWidth(), bounds.getHeight(), 0,
5791 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005792
Vishnu Nair4351ad52019-02-11 14:13:02 -08005793 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005794 drawLayers();
5795 }
5796 }
chaviwa76b2712017-09-20 12:02:26 -07005797
chaviwa76b2712017-09-20 12:02:26 -07005798 private:
chaviw7206d492017-11-10 16:16:12 -08005799 const sp<Layer> mLayer;
5800 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005801
5802 // In the "childrenOnly" case we reparent the children to a screenshot
5803 // layer which has no properties set and which does not draw.
5804 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005805 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005806 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005807
5808 SurfaceFlinger* mFlinger;
5809 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005810 };
5811
Robert Carrc0df3122019-04-11 13:18:21 -07005812 int reqWidth = 0;
5813 int reqHeight = 0;
5814 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005815 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005816 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005817
Robert Carrc0df3122019-04-11 13:18:21 -07005818 {
5819 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005820
Robert Carrc0df3122019-04-11 13:18:21 -07005821 parent = fromHandle(layerHandleBinder);
5822 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5823 ALOGE("captureLayers called with an invalid or removed parent");
5824 return NAME_NOT_FOUND;
5825 }
5826
5827 const int uid = IPCThreadState::self()->getCallingUid();
5828 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5829 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5830 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5831 return PERMISSION_DENIED;
5832 }
5833
5834 if (sourceCrop.width() <= 0) {
5835 crop.left = 0;
5836 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5837 }
5838
5839 if (sourceCrop.height() <= 0) {
5840 crop.top = 0;
5841 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5842 }
5843 reqWidth = crop.width() * frameScale;
5844 reqHeight = crop.height() * frameScale;
5845
5846 for (const auto& handle : excludeHandles) {
5847 sp<Layer> excludeLayer = fromHandle(handle);
5848 if (excludeLayer != nullptr) {
5849 excludeLayers.emplace(excludeLayer);
5850 } else {
5851 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5852 return NAME_NOT_FOUND;
5853 }
5854 }
5855 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005856
Chia-I Wu20261cb2018-08-23 12:55:44 -07005857 // really small crop or frameScale
5858 if (reqWidth <= 0) {
5859 reqWidth = 1;
5860 }
5861 if (reqHeight <= 0) {
5862 reqHeight = 1;
5863 }
5864
Robert Carr866455f2019-04-02 16:28:26 -07005865 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5866 auto traverseLayers = [parent, childrenOnly,
5867 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005868 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5869 if (!layer->isVisible()) {
5870 return;
Robert Carr578038f2018-03-09 12:25:24 -08005871 } else if (childrenOnly && layer == parent.get()) {
5872 return;
chaviwa76b2712017-09-20 12:02:26 -07005873 }
Robert Carr866455f2019-04-02 16:28:26 -07005874
5875 sp<Layer> p = layer;
5876 while (p != nullptr) {
5877 if (excludeLayers.count(p) != 0) {
5878 return;
5879 }
5880 p = p->getParent();
5881 }
5882
chaviwa76b2712017-09-20 12:02:26 -07005883 visitor(layer);
5884 });
5885 };
Robert Carr108b2c72019-04-02 16:32:58 -07005886
5887 bool outCapturedSecureLayers = false;
5888 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5889 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005890}
5891
5892status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5893 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005894 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005895 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005896 bool useIdentityTransform,
5897 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005898 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005899
Peiyong Lin0e003c92018-09-17 11:09:51 -07005900 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005901 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5902 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005903 *outBuffer =
5904 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5905 static_cast<android_pixel_format>(reqPixelFormat), 1,
5906 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005907
Robert Carr108b2c72019-04-02 16:32:58 -07005908 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5909 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005910}
5911
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005912status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5913 TraverseLayersFunction traverseLayers,
5914 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005915 bool useIdentityTransform,
5916 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005917 // This mutex protects syncFd and captureResult for communication of the return values from the
5918 // main thread back to this Binder thread
5919 std::mutex captureMutex;
5920 std::condition_variable captureCondition;
5921 std::unique_lock<std::mutex> captureLock(captureMutex);
5922 int syncFd = -1;
5923 std::optional<status_t> captureResult;
5924
Robert Carr03480e22018-01-04 16:02:06 -08005925 const int uid = IPCThreadState::self()->getCallingUid();
5926 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5927
Dominik Laskowski8c001672018-05-30 16:52:06 -07005928 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005929 // If there is a refresh pending, bug out early and tell the binder thread to try again
5930 // after the refresh.
5931 if (mRefreshPending) {
5932 ATRACE_NAME("Skipping screenshot for now");
5933 std::unique_lock<std::mutex> captureLock(captureMutex);
5934 captureResult = std::make_optional<status_t>(EAGAIN);
5935 captureCondition.notify_one();
5936 return;
5937 }
5938
5939 status_t result = NO_ERROR;
5940 int fd = -1;
5941 {
5942 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005943 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005944 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005945 useIdentityTransform, forSystem, &fd,
5946 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005947 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005948 }
5949
5950 {
5951 std::unique_lock<std::mutex> captureLock(captureMutex);
5952 syncFd = fd;
5953 captureResult = std::make_optional<status_t>(result);
5954 captureCondition.notify_one();
5955 }
5956 });
5957
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005958 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005959 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005960 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005961 while (*captureResult == EAGAIN) {
5962 captureResult.reset();
5963 result = postMessageAsync(message);
5964 if (result != NO_ERROR) {
5965 return result;
5966 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005967 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005968 }
5969 result = *captureResult;
5970 }
5971
5972 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005973 sync_wait(syncFd, -1);
5974 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005975 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005976
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005977 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005978}
5979
chaviwa76b2712017-09-20 12:02:26 -07005980void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005981 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005982 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5983 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005984 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005985
chaviwa76b2712017-09-20 12:02:26 -07005986 const auto reqWidth = renderArea.getReqWidth();
5987 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005988 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005989 const auto transform = renderArea.getTransform();
5990 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005991
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005992 renderengine::DisplaySettings clientCompositionDisplay;
5993 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005994
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005995 // assume that bounds are never offset, and that they are the same as the
5996 // buffer bounds.
5997 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005998 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005999 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006000
6001 // Now take into account the rotation flag. We append a transform that
6002 // rotates the layer stack about the origin, then translate by buffer
6003 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006004 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006005 int displacementX = 0;
6006 int displacementY = 0;
6007 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6008 switch (rotation) {
6009 case ui::Transform::ROT_90:
6010 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006011 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006012 break;
6013 case ui::Transform::ROT_180:
6014 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006015 displacementY = renderArea.getBounds().getWidth();
6016 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006017 break;
6018 case ui::Transform::ROT_270:
6019 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006020 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006021 break;
6022 default:
6023 break;
6024 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006025
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006026 // We need to transform the clipping window into the right spot.
6027 // First, rotate the clipping rectangle by the rotation hint to get the
6028 // right orientation
6029 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6030 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6031 const vec4 rotClipTL = rotMatrix * clipTL;
6032 const vec4 rotClipBR = rotMatrix * clipBR;
6033 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6034 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6035 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6036 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6037
6038 // Now reposition the clipping rectangle with the displacement vector
6039 // computed above.
6040 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006041 clientCompositionDisplay.clip =
6042 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6043 newClipRight + displacementX, newClipBottom + displacementY);
6044
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006045 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006046 clientCompositionDisplay.globalTransform =
6047 clipTransform * clientCompositionDisplay.globalTransform;
6048
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006049 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6050 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006051
chaviw50da5042018-04-09 13:49:37 -07006052 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006053
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006054 renderengine::LayerSettings fillLayer;
6055 fillLayer.source.buffer.buffer = nullptr;
6056 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6057 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6058 fillLayer.alpha = half(alpha);
6059 clientCompositionLayers.push_back(fillLayer);
6060
6061 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006062 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006063 renderengine::LayerSettings layerSettings;
6064 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006065 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006066 if (prepared) {
6067 clientCompositionLayers.push_back(layerSettings);
6068 }
chaviwa76b2712017-09-20 12:02:26 -07006069 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006070
6071 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006072 // Use an empty fence for the buffer fence, since we just created the buffer so
6073 // there is no need for synchronization with the GPU.
6074 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006075 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006076 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006077 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006078 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006079
6080 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006081}
6082
chaviwa76b2712017-09-20 12:02:26 -07006083status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6084 TraverseLayersFunction traverseLayers,
6085 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006086 bool useIdentityTransform, bool forSystem,
6087 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006088 ATRACE_CALL();
6089
chaviwa76b2712017-09-20 12:02:26 -07006090 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006091 outCapturedSecureLayers =
6092 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006093 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006094
Robert Carr03480e22018-01-04 16:02:06 -08006095 // We allow the system server to take screenshots of secure layers for
6096 // use in situations like the Screen-rotation animation and place
6097 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006098 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006099 ALOGW("FB is protected: PERMISSION_DENIED");
6100 return PERMISSION_DENIED;
6101 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006102 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006103 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006104}
6105
chaviw95ef3c42019-02-14 10:55:09 -08006106void SurfaceFlinger::setInputWindowsFinished() {
6107 Mutex::Autolock _l(mStateLock);
6108
6109 mPendingSyncInputWindows = false;
6110 mTransactionCV.broadcast();
6111}
chaviw5f21a5e2019-02-14 10:00:34 -08006112
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006113// ---------------------------------------------------------------------------
6114
Dan Stoza412903f2017-04-27 13:42:17 -07006115void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6116 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006117}
6118
Dan Stoza412903f2017-04-27 13:42:17 -07006119void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6120 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006121}
6122
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006123void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006124 const LayerVector::Visitor& visitor) {
6125 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006126 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006127 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006128 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006129 continue;
6130 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006131 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006132 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006133 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006134 return;
6135 }
chaviwa76b2712017-09-20 12:02:26 -07006136 if (!layer->isVisible()) {
6137 return;
6138 }
6139 visitor(layer);
6140 });
6141 }
6142}
6143
Dominik Laskowski22488f62019-03-28 09:53:04 -07006144void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6145 const std::vector<int32_t>& allowedConfigs) {
6146 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006147 return;
6148 }
6149
6150 ALOGV("Updating allowed configs");
Dominik Laskowski22488f62019-03-28 09:53:04 -07006151 mAllowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(), allowedConfigs.end());
Ady Abraham838de062019-02-04 10:24:03 -08006152
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006153 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006154 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006155 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006156 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006157 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006158 setDesiredActiveConfig(
6159 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006160 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006161 }
6162 }
Ady Abraham838de062019-02-04 10:24:03 -08006163}
6164
Dominik Laskowski22488f62019-03-28 09:53:04 -07006165status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006166 const std::vector<int32_t>& allowedConfigs) {
6167 ATRACE_CALL();
6168
Dominik Laskowski22488f62019-03-28 09:53:04 -07006169 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006170 return BAD_VALUE;
6171 }
6172
Ady Abraham34392f72019-04-10 11:29:27 -07006173 if (mDebugDisplayConfigSetByBackdoor) {
6174 // ignore this request as config is overridden by backdoor
6175 return NO_ERROR;
6176 }
6177
Ady Abraham838de062019-02-04 10:24:03 -08006178 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006179 const auto display = getDisplayDeviceLocked(displayToken);
6180 if (!display) {
6181 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6182 displayToken.get());
6183 } else if (display->isVirtual()) {
6184 ALOGW("Attempt to set allowed display configs for virtual display");
6185 } else {
6186 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6187 }
Ady Abraham838de062019-02-04 10:24:03 -08006188 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006189
Ady Abraham838de062019-02-04 10:24:03 -08006190 return NO_ERROR;
6191}
6192
Dominik Laskowski22488f62019-03-28 09:53:04 -07006193status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006194 std::vector<int32_t>* outAllowedConfigs) {
6195 ATRACE_CALL();
6196
Dominik Laskowski22488f62019-03-28 09:53:04 -07006197 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006198 return BAD_VALUE;
6199 }
6200
Dominik Laskowski22488f62019-03-28 09:53:04 -07006201 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006202
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006203 const auto display = getDisplayDeviceLocked(displayToken);
6204 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006205 return NAME_NOT_FOUND;
6206 }
6207
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006208 if (display->isPrimary()) {
6209 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6210 }
6211
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006212 return NO_ERROR;
6213}
6214
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006215void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006216 mFlinger->setInputWindowsFinished();
6217}
6218
Robert Carrc0df3122019-04-11 13:18:21 -07006219sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6220 BBinder *b = handle->localBinder();
6221 if (b == nullptr) {
6222 return nullptr;
6223 }
6224 auto it = mLayersByLocalBinderToken.find(b);
6225 if (it != mLayersByLocalBinderToken.end()) {
6226 return it->second.promote();
6227 }
6228 return nullptr;
6229}
6230
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006231} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006232
Mathias Agopian3f844832013-08-07 21:24:32 -07006233#if defined(__gl_h_)
6234#error "don't include gl/gl.h in this file"
6235#endif
6236
6237#if defined(__gl2_h_)
6238#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006239#endif