blob: 5c9fb4301421b570e1c97f8cadee0a3a8374142e [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>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
52
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070054#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080055#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080056#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080057#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070059#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <ui/ColorSpace.h>
61#include <ui/DebugUtils.h>
62#include <ui/DisplayInfo.h>
63#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070064#include <ui/GraphicBufferAllocator.h>
65#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070066#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080067#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070068#include <utils/String16.h>
69#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070070#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080071#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070072#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopian921e6ac2012-07-23 23:11:29 -070074#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070075#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076
Robert Carr578038f2018-03-09 12:25:24 -080077#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070078#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070079#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020082#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080084#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080085#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070086#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080087#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070088#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070089#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070092#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093
Steven Thomasb02664d2017-07-26 18:48:28 -070094#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070095#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070096#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070097#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070098#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070099#include "Effects/Daltonizer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700100#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700101#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700102#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700103#include "Scheduler/EventControlThread.h"
104#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700105#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700106#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700107#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700108#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800109#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700110
Mathias Agopianff2ed702013-09-01 21:36:12 -0700111#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700112
David Sodman7e4ae112018-02-09 15:02:28 -0800113#include "android-base/stringprintf.h"
114
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900115#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800116#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
117#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700118#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900119#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900120
chaviw1d044282017-09-27 12:19:28 -0700121#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900122#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700123
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800124namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700125
Jaesoo Lee43518572017-01-23 19:03:16 +0900126using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900127using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900128using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800129
Ady Abraham8532d012019-05-08 14:50:56 -0700130using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800131using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700132using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700133using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800134using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700135using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700136using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900137
Steven Thomasb02664d2017-07-26 18:48:28 -0700138namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700139
140#pragma clang diagnostic push
141#pragma clang diagnostic error "-Wswitch-enum"
142
143bool isWideColorMode(const ColorMode colorMode) {
144 switch (colorMode) {
145 case ColorMode::DISPLAY_P3:
146 case ColorMode::ADOBE_RGB:
147 case ColorMode::DCI_P3:
148 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700149 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700150 case ColorMode::BT2100_PQ:
151 case ColorMode::BT2100_HLG:
152 return true;
153 case ColorMode::NATIVE:
154 case ColorMode::STANDARD_BT601_625:
155 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
156 case ColorMode::STANDARD_BT601_525:
157 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
158 case ColorMode::STANDARD_BT709:
159 case ColorMode::SRGB:
160 return false;
161 }
162 return false;
163}
164
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700165bool isHdrColorMode(const ColorMode colorMode) {
166 switch (colorMode) {
167 case ColorMode::BT2100_PQ:
168 case ColorMode::BT2100_HLG:
169 return true;
170 case ColorMode::DISPLAY_P3:
171 case ColorMode::ADOBE_RGB:
172 case ColorMode::DCI_P3:
173 case ColorMode::BT2020:
174 case ColorMode::DISPLAY_BT2020:
175 case ColorMode::NATIVE:
176 case ColorMode::STANDARD_BT601_625:
177 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
178 case ColorMode::STANDARD_BT601_525:
179 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
180 case ColorMode::STANDARD_BT709:
181 case ColorMode::SRGB:
182 return false;
183 }
184 return false;
185}
186
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700187ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
188 switch (rotation) {
189 case ISurfaceComposer::eRotateNone:
190 return ui::Transform::ROT_0;
191 case ISurfaceComposer::eRotate90:
192 return ui::Transform::ROT_90;
193 case ISurfaceComposer::eRotate180:
194 return ui::Transform::ROT_180;
195 case ISurfaceComposer::eRotate270:
196 return ui::Transform::ROT_270;
197 }
198 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
199 return ui::Transform::ROT_0;
200}
201
Peiyong Linfca547f2018-07-09 13:03:33 -0700202#pragma clang diagnostic pop
203
Steven Thomasb02664d2017-07-26 18:48:28 -0700204class ConditionalLock {
205public:
206 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
207 if (lock) {
208 mMutex.lock();
209 }
210 }
211 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
212private:
213 Mutex& mMutex;
214 bool mLocked;
215};
Peiyong Linfca547f2018-07-09 13:03:33 -0700216
Peiyong Lin9d846a52018-11-05 13:18:20 -0800217// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
218bool validateCompositionDataspace(Dataspace dataspace) {
219 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
220}
221
Steven Thomasb02664d2017-07-26 18:48:28 -0700222} // namespace anonymous
223
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800224// ---------------------------------------------------------------------------
225
Mathias Agopian99b49842011-06-27 16:05:52 -0700226const String16 sHardwareTest("android.permission.HARDWARE_TEST");
227const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
228const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
229const String16 sDump("android.permission.DUMP");
230
231// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700232int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700233bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800234uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800235bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800236bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800237int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600238bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700239int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700240bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700241bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700242Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
243ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
244Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
245ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700246
Kalle Raitaa099a242017-01-11 11:17:29 -0800247std::string getHwcServiceName() {
248 char value[PROPERTY_VALUE_MAX] = {};
249 property_get("debug.sf.hwc_service_name", value, "default");
250 ALOGI("Using HWComposer service: '%s'", value);
251 return std::string(value);
252}
253
254bool useTrebleTestingOverride() {
255 char value[PROPERTY_VALUE_MAX] = {};
256 property_get("debug.sf.treble_testing_override", value, "false");
257 ALOGI("Treble testing override: '%s'", value);
258 return std::string(value) == "true";
259}
260
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800261std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
262 switch(displayColorSetting) {
263 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700264 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800265 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700266 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800267 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700268 return std::string("Enhanced");
269 default:
270 return std::string("Unknown ") +
271 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800272 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800273}
274
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700275SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800276
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700277SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
278 : mFactory(factory),
279 mPhaseOffsets(mFactory.createPhaseOffsets()),
280 mInterceptor(mFactory.createSurfaceInterceptor(this)),
281 mTimeStats(mFactory.createTimeStats()),
282 mEventQueue(mFactory.createMessageQueue()),
283 mCompositionEngine(mFactory.createCompositionEngine()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800284
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700285SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800286 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700291
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900292 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700293
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700302
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900303 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 mDefaultCompositionDataspace =
306 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700307 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
308 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 defaultCompositionDataspace = mDefaultCompositionDataspace;
310 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
311 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
312 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
313 wideColorGamutCompositionPixelFormat =
314 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700315
Yichi Chenda901bf2019-06-28 14:58:27 +0800316 mColorSpaceAgnosticDataspace =
317 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
318
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900319 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800320
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900321 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
322 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
323 switch (tmpPrimaryDisplayOrientation) {
324 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700325 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900327 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700328 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900330 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700331 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800338
Sundong Ahn85131bd2019-02-18 15:51:53 +0900339 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 // debugging stuff...
342 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343
Mathias Agopianb4b17302013-03-20 18:36:41 -0700344 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700345 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 property_get("debug.sf.showupdates", value, "0");
348 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700350 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000351
352 // DDMS debugging deprecated (b/120782499)
353 property_get("debug.sf.ddms", value, "0");
354 int debugDdms = atoi(value);
355 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700356
357 property_get("debug.sf.disable_backpressure", value, "0");
358 mPropagateBackpressure = !atoi(value);
359 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700360
Ady Abrahamadb9a992019-09-19 21:21:55 +0000361 property_get("debug.sf.enable_gl_backpressure", value, "0");
362 mPropagateBackpressureClientComposition = atoi(value);
363 ALOGI_IF(mPropagateBackpressureClientComposition,
364 "Enabling backpressure propagation for Client Composition");
365
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800366 property_get("debug.sf.enable_hwc_vds", value, "0");
367 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800368 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800370 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800371 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700373
Yiwei Zhang243b3782018-05-15 17:40:04 -0700374 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700375 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
376 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
377
Ana Krulece5a06e02019-03-06 17:09:03 -0800378 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800379 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800380
381 int int_value = atoi(value);
382 if (int_value) {
383 mUseSmart90ForVideo = true;
384 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800385
Dan Stozaec460082018-12-17 15:35:09 -0800386 property_get("debug.sf.luma_sampling", value, "1");
387 mLumaSampling = atoi(value);
388
Ana Krulec757f63a2019-01-25 10:46:18 -0800389 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700390 mVsyncModulator.setPhaseOffsets(early, gl, late,
391 mPhaseOffsets->getOffsetThresholdForNextVsync());
Dan Stoza84d619e2018-03-28 17:07:36 -0700392
Romain Guy11d63f42017-07-20 12:47:14 -0700393 // We should be reading 'persist.sys.sf.color_saturation' here
394 // but since /data may be encrypted, we need to wait until after vold
395 // comes online to attempt to read the property. The property is
396 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800397
398 if (useTrebleTestingOverride()) {
399 // Without the override SurfaceFlinger cannot connect to HIDL
400 // services that are not listed in the manifests. Considered
401 // deriving the setting from the set service name, but it
402 // would be brittle if the name that's not 'default' is used
403 // for production purposes later on.
404 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
405 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406}
407
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408void SurfaceFlinger::onFirstRef()
409{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800410 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700413SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414
Dan Stozac7014012014-02-14 15:03:43 -0800415void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416{
417 // the window manager died on us. prepare its eulogy.
418
Andy McFadden13a082e2012-08-24 10:16:42 -0700419 // restore initial conditions (default device unblank, etc)
420 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800421
422 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700423 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800424}
425
Robert Carr1db73f62016-12-21 12:58:51 -0800426static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700427 status_t err = client->initCheck();
428 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800429 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800430 }
Robert Carr1db73f62016-12-21 12:58:51 -0800431 return nullptr;
432}
433
434sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
435 return initClient(new Client(this));
436}
437
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700438sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
439 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440{
441 class DisplayToken : public BBinder {
442 sp<SurfaceFlinger> flinger;
443 virtual ~DisplayToken() {
444 // no more references, this display must be terminated
445 Mutex::Autolock _l(flinger->mStateLock);
446 flinger->mCurrentState.displays.removeItem(this);
447 flinger->setTransactionFlags(eDisplayTransactionNeeded);
448 }
449 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700450 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700451 : flinger(flinger) {
452 }
453 };
454
455 sp<BBinder> token = new DisplayToken(this);
456
457 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458 // Display ID is assigned when virtual display is allocated by HWC.
459 DisplayDeviceState state;
460 state.isSecure = secure;
461 state.displayName = displayName;
462 mCurrentState.displays.add(token, state);
463 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700464 return token;
465}
466
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700467void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700468 Mutex::Autolock _l(mStateLock);
469
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
471 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700472 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700473 return;
474 }
475
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
477 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 ALOGE("destroyDisplay called for non-virtual display");
479 return;
480 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 mInterceptor->saveDisplayDeletion(state.sequenceId);
482 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700483 setTransactionFlags(eDisplayTransactionNeeded);
484}
485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800486std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
487 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800489 const auto internalDisplayId = getInternalDisplayIdLocked();
490 if (!internalDisplayId) {
491 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 }
493
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800494 std::vector<PhysicalDisplayId> displayIds;
495 displayIds.reserve(mPhysicalDisplayTokens.size());
496 displayIds.push_back(internalDisplayId->value);
497
498 for (const auto& [id, token] : mPhysicalDisplayTokens) {
499 if (id != *internalDisplayId) {
500 displayIds.push_back(id.value);
501 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700503
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800504 return displayIds;
505}
506
507sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
508 Mutex::Autolock lock(mStateLock);
509 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700510}
511
Ady Abraham37965d42018-11-01 13:43:32 -0700512status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
513 if (!outGetColorManagement) {
514 return BAD_VALUE;
515 }
516 *outGetColorManagement = useColorManagement;
517 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700518}
519
Lloyd Pique441d5042018-10-18 16:49:51 -0700520HWComposer& SurfaceFlinger::getHwComposer() const {
521 return mCompositionEngine->getHwComposer();
522}
523
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700524renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
525 return mCompositionEngine->getRenderEngine();
526}
527
Lloyd Pique70d91362018-10-18 16:02:55 -0700528compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
529 return *mCompositionEngine.get();
530}
531
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532void SurfaceFlinger::bootFinished()
533{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700534 if (mStartPropertySetThread->join() != NO_ERROR) {
535 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 const nsecs_t now = systemTime();
538 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000539 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540
541 // wait patiently for the window manager death
542 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700543 mWindowManager = defaultServiceManager()->getService(name);
544 if (mWindowManager != 0) {
545 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 }
Robert Carr720e5062018-07-30 17:45:14 -0700547 sp<IBinder> input(defaultServiceManager()->getService(
548 String16("inputflinger")));
549 if (input == nullptr) {
550 ALOGE("Failed to link to input service");
551 } else {
552 mInputFlinger = interface_cast<IInputFlinger>(input);
553 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 if (mVrFlinger) {
556 mVrFlinger->OnBootFinished();
557 }
558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700560 // formerly we would just kill the process, but we now ask it to exit so it
561 // can choose where to stop the animation.
562 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700563
564 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
565 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
566 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700567
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800569 readPersistentProperties();
570 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571
Steven Thomase9eb1832019-08-28 16:08:35 -0700572 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
573 // set the refresh rate according to the policy
574 const auto& performanceRefreshRate =
575 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800576
Steven Thomase9eb1832019-08-28 16:08:35 -0700577 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
578 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
579 } else {
580 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::Changed);
581 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800582 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800583 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800584}
585
Dan Stoza436ccf32018-06-21 12:10:12 -0700586uint32_t SurfaceFlinger::getNewTexture() {
587 {
588 std::lock_guard lock(mTexturePoolMutex);
589 if (!mTexturePool.empty()) {
590 uint32_t name = mTexturePool.back();
591 mTexturePool.pop_back();
592 ATRACE_INT("TexturePoolSize", mTexturePool.size());
593 return name;
594 }
595
596 // The pool was too small, so increase it for the future
597 ++mTexturePoolSize;
598 }
599
600 // The pool was empty, so we need to get a new texture name directly using a
601 // blocking call to the main thread
602 uint32_t name = 0;
603 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
604 return name;
605}
606
Mathias Agopian3f844832013-08-07 21:24:32 -0700607void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700608 std::lock_guard lock(mTexturePoolMutex);
609 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
610 // to actually delete this or not based on mTexturePoolSize
611 mTexturePool.push_back(texture);
612 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700613}
614
Wei Wangf9b05ee2017-07-19 20:59:39 -0700615// Do not call property_set on main thread which will be blocked by init
616// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700617void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700618 ALOGI( "SurfaceFlinger's main thread ready to run. "
619 "Initializing graphics H/W...");
620
Ana Krulec757f63a2019-01-25 10:46:18 -0800621 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900622
Steven Thomasb02664d2017-07-26 18:48:28 -0700623 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700626 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700627 renderEngineFeature |= (useColorManagement ?
628 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700629 renderEngineFeature |= (useContextPriority ?
630 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700631 renderEngineFeature |=
632 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
633 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700634
635 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800636 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700637 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700638 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800639 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700640
641 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
642 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700643 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
644 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800645 // Process any initial hotplug and resulting display changes.
646 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 const auto display = getDefaultDisplayDeviceLocked();
648 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700649 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700650 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800651
Steven Thomas050b2c82017-03-06 11:45:16 -0800652 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700653 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700654 // This callback is called from the vr flinger dispatch thread. We
655 // need to call signalTransaction(), which requires holding
656 // mStateLock when we're not on the main thread. Acquiring
657 // mStateLock from the vr flinger dispatch thread might trigger a
658 // deadlock in surface flinger (see b/66916578), so post a message
659 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700660 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700661 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
662 mVrFlingerRequestsDisplay = requestDisplay;
663 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700664 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
667 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700668 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700669 .value_or(0),
670 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 if (!mVrFlinger) {
672 ALOGE("Failed to start vrflinger");
673 }
674 }
675
Mathias Agopian92a979a2012-08-02 18:32:23 -0700676 // initialize our drawing state
677 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700678
Andy McFadden13a082e2012-08-24 10:16:42 -0700679 // set initial conditions (e.g. unblank default device)
680 initializeDisplays();
681
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700682 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700683
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700685
686 const bool presentFenceReliable =
687 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
688 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700689
690 if (mStartPropertySetThread->Start() != NO_ERROR) {
691 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800692 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800693
Dan Stoza9e56aa02015-11-02 13:00:03 -0800694 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700695}
696
Romain Guy11d63f42017-07-20 12:47:14 -0700697void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700698 Mutex::Autolock _l(mStateLock);
699
Romain Guy11d63f42017-07-20 12:47:14 -0700700 char value[PROPERTY_VALUE_MAX];
701
702 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800703 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700704 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800705 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100706
707 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700708 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800709
710 property_get("persist.sys.sf.color_mode", value, "0");
711 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700712}
713
Mathias Agopiana67e4182012-06-19 17:26:12 -0700714void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800715 // Start boot animation service by setting a property mailbox
716 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800718 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719 if (mStartPropertySetThread->join() != NO_ERROR) {
720 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800721 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700725 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
Mathias Agopian875d8e12013-06-07 15:35:48 -0700728size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700729 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700730}
731
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800733
Jamie Gennis582270d2011-08-17 18:19:00 -0700734bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800735 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800736 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800737 return authenticateSurfaceTextureLocked(bufferProducer);
738}
739
740bool SurfaceFlinger::authenticateSurfaceTextureLocked(
741 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800742 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800743 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800744}
745
Brian Anderson6b376712017-04-04 10:51:39 -0700746status_t SurfaceFlinger::getSupportedFrameTimestamps(
747 std::vector<FrameEvent>* outSupported) const {
748 *outSupported = {
749 FrameEvent::REQUESTED_PRESENT,
750 FrameEvent::ACQUIRE,
751 FrameEvent::LATCH,
752 FrameEvent::FIRST_REFRESH_START,
753 FrameEvent::LAST_REFRESH_START,
754 FrameEvent::GPU_COMPOSITION_DONE,
755 FrameEvent::DEQUEUE_READY,
756 FrameEvent::RELEASE,
757 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700758 ConditionalLock _l(mStateLock,
759 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700760 if (!getHwComposer().hasCapability(
761 HWC2::Capability::PresentFenceIsNotReliable)) {
762 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
763 }
764 return NO_ERROR;
765}
766
Dominik Laskowski22488f62019-03-28 09:53:04 -0700767status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
768 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700769 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700770 return BAD_VALUE;
771 }
772
Dominik Laskowski22488f62019-03-28 09:53:04 -0700773 Mutex::Autolock lock(mStateLock);
774
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800775 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700776 if (!displayId) {
777 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700778 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700779
Mathias Agopian8b736f12012-08-13 17:54:26 -0700780 // TODO: Not sure if display density should handled by SF any longer
781 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700782 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700783 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700784 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800785 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700786 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700787 }
788 return density;
789 }
790 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700791 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700792 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700793 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700794 return getDensityFromProperty("ro.sf.lcd_density"); }
795 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700796
Dan Stoza7f7da322014-05-02 15:26:25 -0700797 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700798
Dominik Laskowski075d3172018-05-24 15:50:06 -0700799 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700800 DisplayInfo info = DisplayInfo();
801
Dan Stoza9e56aa02015-11-02 13:00:03 -0800802 float xdpi = hwConfig->getDpiX();
803 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700804
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700805 info.w = hwConfig->getWidth();
806 info.h = hwConfig->getHeight();
807 // Default display viewport to display width and height
808 info.viewportW = info.w;
809 info.viewportH = info.h;
810
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800811 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 // The density of the device is provided by a build property
813 float density = Density::getBuildDensity() / 160.0f;
814 if (density == 0) {
815 // the build doesn't provide a density -- this is wrong!
816 // use xdpi instead
817 ALOGE("ro.sf.lcd_density must be defined as a build property");
818 density = xdpi / 160.0f;
819 }
820 if (Density::getEmuDensity()) {
821 // if "qemu.sf.lcd_density" is specified, it overrides everything
822 xdpi = ydpi = density = Density::getEmuDensity();
823 density /= 160.0f;
824 }
825 info.density = density;
826
827 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700828 const auto display = getDefaultDisplayDeviceLocked();
829 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700830
831 // This is for screenrecord
832 const Rect viewport = display->getViewport();
833 if (viewport.isValid()) {
834 info.viewportW = uint32_t(viewport.getWidth());
835 info.viewportH = uint32_t(viewport.getHeight());
836 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 } else {
838 // TODO: where should this value come from?
839 static const int TV_DENSITY = 213;
840 info.density = TV_DENSITY / 160.0f;
841 info.orientation = 0;
842 }
843
Dan Stoza7f7da322014-05-02 15:26:25 -0700844 info.xdpi = xdpi;
845 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800846 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomase9eb1832019-08-28 16:08:35 -0700847 const auto refreshRateType =
848 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700849 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
850 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800851
Andy McFadden91b2ca82014-06-13 14:04:23 -0700852 // This is how far in advance a buffer must be queued for
853 // presentation at a given time. If you want a buffer to appear
854 // on the screen at time N, you must submit the buffer before
855 // (N - presentationDeadline).
856 //
857 // Normally it's one full refresh period (to give SF a chance to
858 // latch the buffer), but this can be reduced by configuring a
859 // DispSync offset. Any additional delays introduced by the hardware
860 // composer or panel must be accounted for here.
861 //
862 // We add an additional 1ms to allow for processing time and
863 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700864 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700865
866 // All non-virtual displays are currently considered secure.
867 info.secure = true;
868
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800869 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700870 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800871 std::swap(info.w, info.h);
872 }
873
Michael Wright28f24d02016-07-12 13:30:53 -0700874 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700875 }
876
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 return NO_ERROR;
878}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700879
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700880status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
881 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700882 return BAD_VALUE;
883 }
884
Ana Krulecc2870422019-01-29 19:00:58 -0800885 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700886 return NO_ERROR;
887}
888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
890 const auto display = getDisplayDevice(displayToken);
891 if (!display) {
892 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800893 return BAD_VALUE;
894 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700895
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700896 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700897}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700898
Ady Abraham03b02dd2019-03-21 15:40:11 -0700899void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800900 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800901
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800902 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800903 // config twice. However event generation config might have changed so we need to update it
904 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800905 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700906 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
907 mDesiredActiveConfig = info;
908 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800909
910 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800911 // This will trigger HWC refresh without resetting the idle timer.
912 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700913 // Start receiving vsync samples now, so that we can detect a period
914 // switch.
915 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700916 // As we called to set period, we will call to onRefreshRateChangeCompleted once
917 // DispSync model is locked.
918 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700919 mPhaseOffsets->setRefreshRateType(info.type);
920 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700921 mVsyncModulator.setPhaseOffsets(early, gl, late,
922 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800923 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800924 mDesiredActiveConfigChanged = true;
925 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700926
927 if (mRefreshRateOverlay) {
928 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
929 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800930}
931
932status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
933 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800934
935 std::vector<int32_t> allowedConfig;
936 allowedConfig.push_back(mode);
937
938 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800939}
940
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800941void SurfaceFlinger::setActiveConfigInternal() {
942 ATRACE_CALL();
943
Dominik Laskowski22488f62019-03-28 09:53:04 -0700944 const auto display = getDefaultDisplayDeviceLocked();
945 if (!display) {
946 return;
947 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800948
Dominik Laskowski22488f62019-03-28 09:53:04 -0700949 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomase9eb1832019-08-28 16:08:35 -0700950 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
951 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700952
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800953 display->setActiveConfig(mUpcomingActiveConfig.configId);
954
Alec Mouri754c98a2019-03-18 18:53:42 -0700955 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -0800956 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700957 mVsyncModulator.setPhaseOffsets(early, gl, late,
958 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800959 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700960
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800961 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800962 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
963 mUpcomingActiveConfig.configId);
964 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965}
966
Ady Abraham53852a52019-05-28 18:07:44 -0700967void SurfaceFlinger::desiredActiveConfigChangeDone() {
968 std::lock_guard<std::mutex> lock(mActiveConfigLock);
969 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
970 mDesiredActiveConfigChanged = false;
971 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
972
973 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
974 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
975 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700976 mVsyncModulator.setPhaseOffsets(early, gl, late,
977 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -0700978}
979
Dominik Laskowski22488f62019-03-28 09:53:04 -0700980bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800981 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800982 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700983 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800984 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700985 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800986 return true;
987 }
988
989 // We received the present fence from the HWC, so we assume it successfully updated
990 // the config, hence we update SF.
991 mCheckPendingFence = false;
992 setActiveConfigInternal();
993 }
994
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995 // Store the local variable to release the lock.
996 ActiveConfigInfo desiredActiveConfig;
997 {
998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800999 if (!mDesiredActiveConfigChanged) {
1000 return false;
1001 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002 desiredActiveConfig = mDesiredActiveConfig;
1003 }
1004
Dominik Laskowski22488f62019-03-28 09:53:04 -07001005 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1007 // display is not valid or we are already in the requested mode
1008 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001009 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001011 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001012
Ady Abraham838de062019-02-04 10:24:03 -08001013 // Desired active config was set, it is different than the config currently in use, however
1014 // allowed configs might have change by the time we process the refresh.
1015 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001016 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001017 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001018 return false;
1019 }
Alec Mouri7f015182019-07-11 13:56:22 -07001020
Ady Abrahamb838aed2019-02-12 15:30:16 -08001021 mUpcomingActiveConfig = desiredActiveConfig;
1022 const auto displayId = display->getId();
1023 LOG_ALWAYS_FATAL_IF(!displayId);
1024
1025 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1026 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1027
1028 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001029 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001030 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001032}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1035 Vector<ColorMode>* outColorModes) {
1036 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001037 return BAD_VALUE;
1038 }
1039
Peiyong Lina52f0292018-03-14 17:26:31 -07001040 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001041 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001042 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001043 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1044
1045 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1046 if (!displayId) {
1047 return NAME_NOT_FOUND;
1048 }
1049
Dominik Laskowski075d3172018-05-24 15:50:06 -07001050 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001051 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001052 }
Michael Wright28f24d02016-07-12 13:30:53 -07001053 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001054
1055 // If it's built-in display and the configuration claims it's not wide color capable,
1056 // filter out all wide color modes. The typical reason why this happens is that the
1057 // hardware is not good enough to support GPU composition of wide color, and thus the
1058 // OEMs choose to disable this capability.
1059 if (isInternalDisplay && !hasWideColorDisplay) {
1060 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1061 isWideColorMode);
1062 } else {
1063 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1064 }
Michael Wright28f24d02016-07-12 13:30:53 -07001065
1066 return NO_ERROR;
1067}
1068
Daniel Solomon42d04562019-01-20 21:03:19 -08001069status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1070 ui::DisplayPrimaries &primaries) {
1071 if (!displayToken) {
1072 return BAD_VALUE;
1073 }
1074
1075 // Currently we only support this API for a single internal display.
1076 if (getInternalDisplayToken() != displayToken) {
1077 return BAD_VALUE;
1078 }
1079
1080 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1081 return NO_ERROR;
1082}
1083
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001084ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1085 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001086 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001087 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001088 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001089}
1090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001092 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093 Vector<ColorMode> modes;
1094 getDisplayColorModes(displayToken, &modes);
1095 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1096 if (mode < ColorMode::NATIVE || !exists) {
1097 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1098 decodeColorMode(mode).c_str(), mode, displayToken.get());
1099 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001100 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101 const auto display = getDisplayDevice(displayToken);
1102 if (!display) {
1103 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1104 decodeColorMode(mode).c_str(), mode, displayToken.get());
1105 } else if (display->isVirtual()) {
1106 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1107 decodeColorMode(mode).c_str(), mode);
1108 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001109 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1110 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111 }
1112 }));
1113
Michael Wright28f24d02016-07-12 13:30:53 -07001114 return NO_ERROR;
1115}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001116
Svetoslavd85084b2014-03-20 10:28:31 -07001117status_t SurfaceFlinger::clearAnimationFrameStats() {
1118 Mutex::Autolock _l(mStateLock);
1119 mAnimFrameTracker.clearStats();
1120 return NO_ERROR;
1121}
1122
1123status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1124 Mutex::Autolock _l(mStateLock);
1125 mAnimFrameTracker.getStats(outStats);
1126 return NO_ERROR;
1127}
1128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1130 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001131 Mutex::Autolock _l(mStateLock);
1132
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001133 const auto display = getDisplayDeviceLocked(displayToken);
1134 if (!display) {
1135 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001136 return BAD_VALUE;
1137 }
1138
Peiyong Linfb069302018-04-25 14:34:31 -07001139 // At this point the DisplayDeivce should already be set up,
1140 // meaning the luminance information is already queried from
1141 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001142 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001143 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1144 capabilities.getDesiredMaxLuminance(),
1145 capabilities.getDesiredMaxAverageLuminance(),
1146 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001147
1148 return NO_ERROR;
1149}
1150
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001151status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1152 ui::PixelFormat* outFormat,
1153 ui::Dataspace* outDataspace,
1154 uint8_t* outComponentMask) const {
1155 if (!outFormat || !outDataspace || !outComponentMask) {
1156 return BAD_VALUE;
1157 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001158 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001159 if (!display || !display->getId()) {
1160 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1161 return BAD_VALUE;
1162 }
1163 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1164 outDataspace, outComponentMask);
1165}
1166
Kevin DuBois74e53772018-11-19 10:52:38 -08001167status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1168 bool enable, uint8_t componentMask,
1169 uint64_t maxFrames) const {
1170 const auto display = getDisplayDevice(displayToken);
1171 if (!display || !display->getId()) {
1172 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1173 return BAD_VALUE;
1174 }
1175
1176 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1177 componentMask, maxFrames);
1178}
1179
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001180status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1181 uint64_t maxFrames, uint64_t timestamp,
1182 DisplayedFrameStats* outStats) const {
1183 const auto display = getDisplayDevice(displayToken);
1184 if (!display || !display->getId()) {
1185 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1186 return BAD_VALUE;
1187 }
1188
1189 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1190 outStats);
1191}
1192
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001193status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1194 if (!outSupported) {
1195 return BAD_VALUE;
1196 }
1197 *outSupported = getRenderEngine().supportsProtectedContent();
1198 return NO_ERROR;
1199}
1200
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001201status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1202 bool* outIsWideColorDisplay) const {
1203 if (!displayToken || !outIsWideColorDisplay) {
1204 return BAD_VALUE;
1205 }
1206 Mutex::Autolock _l(mStateLock);
1207 const auto display = getDisplayDeviceLocked(displayToken);
1208 if (!display) {
1209 return BAD_VALUE;
1210 }
Peiyong Linff84a152019-05-17 18:36:19 -07001211
1212 // Use hasWideColorDisplay to override built-in display.
1213 const auto displayId = display->getId();
1214 if (displayId && displayId == getInternalDisplayIdLocked()) {
1215 *outIsWideColorDisplay = hasWideColorDisplay;
1216 return NO_ERROR;
1217 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001218 *outIsWideColorDisplay = display->hasWideColorGamut();
1219 return NO_ERROR;
1220}
1221
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001222status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001223 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001224 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001225
Chia-I Wu90f669f2017-10-05 14:24:41 -07001226 if (mInjectVSyncs == enable) {
1227 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001228 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001229
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001230 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001231 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001232 if (enable) {
1233 ALOGV("VSync Injections enabled");
1234 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001235 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001236 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001237 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001238 impl::EventThread::InterceptVSyncsCallback(),
1239 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001240 }
Steven Thomase9eb1832019-08-28 16:08:35 -07001241 mEventQueue->setEventThread(mInjectorEventThread.get(), [&] { mScheduler->resync(); });
Chia-I Wu90f669f2017-10-05 14:24:41 -07001242 } else {
1243 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001244 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
Steven Thomase9eb1832019-08-28 16:08:35 -07001245 [&] { mScheduler->resync(); });
Chia-I Wu90f669f2017-10-05 14:24:41 -07001246 }
1247
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001248 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001249 }));
1250
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001251 return NO_ERROR;
1252}
1253
1254status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001255 Mutex::Autolock _l(mStateLock);
1256
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001257 if (!mInjectVSyncs) {
1258 ALOGE("VSync Injections not enabled");
1259 return BAD_VALUE;
1260 }
1261 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1262 ALOGV("Injecting VSync inside SurfaceFlinger");
1263 mVSyncInjector->onInjectSyncEvent(when);
1264 }
1265 return NO_ERROR;
1266}
1267
Lloyd Pique755e3192018-01-31 16:46:15 -08001268status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1269 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001270 // Try to acquire a lock for 1s, fail gracefully
1271 const status_t err = mStateLock.timedLock(s2ns(1));
1272 const bool locked = (err == NO_ERROR);
1273 if (!locked) {
1274 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1275 return TIMED_OUT;
1276 }
1277
1278 outLayers->clear();
1279 mCurrentState.traverseInZOrder([&](Layer* layer) {
1280 outLayers->push_back(layer->getLayerDebugInfo());
1281 });
1282
1283 mStateLock.unlock();
1284 return NO_ERROR;
1285}
1286
Peiyong Linc6780972018-10-28 15:24:08 -07001287status_t SurfaceFlinger::getCompositionPreference(
1288 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1289 Dataspace* outWideColorGamutDataspace,
1290 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001291 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001292 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001293 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001294 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001295 return NO_ERROR;
1296}
1297
Dan Stozaec460082018-12-17 15:35:09 -08001298status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1299 const sp<IBinder>& stopLayerHandle,
1300 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001301 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001302 return BAD_VALUE;
1303 }
1304 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001305 return NO_ERROR;
1306}
1307
Dan Stozaec460082018-12-17 15:35:09 -08001308status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001309 if (!listener) {
1310 return BAD_VALUE;
1311 }
Dan Stozaec460082018-12-17 15:35:09 -08001312 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001313 return NO_ERROR;
1314}
Dan Gittik57e63c52019-01-18 16:37:54 +00001315
1316status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1317 bool* outSupport) const {
1318 if (!displayToken || !outSupport) {
1319 return BAD_VALUE;
1320 }
1321 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1322 if (!displayId) {
1323 return NAME_NOT_FOUND;
1324 }
1325 *outSupport =
1326 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1327 return NO_ERROR;
1328}
1329
1330status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1331 float brightness) const {
1332 if (!displayToken) {
1333 return BAD_VALUE;
1334 }
1335 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1336 if (!displayId) {
1337 return NAME_NOT_FOUND;
1338 }
1339 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1340}
1341
Ady Abraham8532d012019-05-08 14:50:56 -07001342status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1343 PowerHint powerHint = static_cast<PowerHint>(hintId);
1344
1345 if (powerHint == PowerHint::INTERACTION) {
1346 mScheduler->notifyTouchEvent();
1347 }
1348
1349 return NO_ERROR;
1350}
1351
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001352// ----------------------------------------------------------------------------
1353
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001354sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001355 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001356 const auto& handle =
1357 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001358
Steven Thomase9eb1832019-08-28 16:08:35 -07001359 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001360}
1361
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001362// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001363
1364void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001365 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001366}
1367
1368void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001369 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001370 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001371}
1372
1373void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001374 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001375 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001376}
1377
1378void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001379 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001380 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001381}
1382
1383status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001384 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001385 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001386}
1387
1388status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001389 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001390 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001391 if (res == NO_ERROR) {
1392 msg->wait();
1393 }
1394 return res;
1395}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001396
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001397void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001398 do {
1399 waitForEvent();
1400 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001401}
1402
Dominik Laskowski83b88212018-12-11 13:34:06 -08001403nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001404 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001405 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1406 return 0;
1407 }
1408
1409 const auto config = getHwComposer().getActiveConfig(*displayId);
1410 return config ? config->getVsyncPeriod() : 0;
1411}
1412
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001413void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1414 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001415 ATRACE_NAME("SF onVsync");
1416
Steven Thomas3cfac282017-02-06 12:29:30 -08001417 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001418 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001419 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001420 return;
1421 }
1422
Dominik Laskowski075d3172018-05-24 15:50:06 -07001423 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001424 return;
1425 }
1426
Dominik Laskowski075d3172018-05-24 15:50:06 -07001427 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001428 // For now, we don't do anything with external display vsyncs.
1429 return;
1430 }
1431
Alec Mourif8e689c2019-05-20 18:32:22 -07001432 bool periodFlushed = false;
1433 mScheduler->addResyncSample(timestamp, &periodFlushed);
1434 if (periodFlushed) {
1435 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001436 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001437}
1438
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001439void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001440 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1441 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001442}
1443
Dominik Laskowski22488f62019-03-28 09:53:04 -07001444bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1445 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001446}
1447
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001448void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001449 const auto display = getDefaultDisplayDeviceLocked();
1450 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001451 return;
1452 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001453 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001454
Ana Krulec7d1d6832018-12-27 11:10:09 -08001455 // Don't do any updating if the current fps is the same as the new one.
Steven Thomase9eb1832019-08-28 16:08:35 -07001456 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1457 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001458
Dominik Laskowski22488f62019-03-28 09:53:04 -07001459 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001460 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1461 return;
1462 }
1463
Dominik Laskowski22488f62019-03-28 09:53:04 -07001464 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001465}
1466
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001467void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001468 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001469 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001470 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001471
Lloyd Piqueba04e622017-12-14 17:11:26 -08001472 // Ignore events that do not have the right sequenceId.
1473 if (sequenceId != getBE().mComposerSequenceId) {
1474 return;
1475 }
1476
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 // Only lock if we're not on the main thread. This function is normally
1478 // called on a hwbinder thread, but for the primary display it's called on
1479 // the main thread with the state lock already held, so don't attempt to
1480 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001481 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001482
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001483 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001484
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001485 if (std::this_thread::get_id() == mMainThreadId) {
1486 // Process all pending hot plug events immediately if we are on the main thread.
1487 processDisplayHotplugEventsLocked();
1488 }
1489
Lloyd Piqueba04e622017-12-14 17:11:26 -08001490 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001491}
1492
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001493void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001494 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001495 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001497 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001498 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001499}
1500
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001501void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001502 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001503
1504 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1505 // display power state.
1506 postMessageAsync(new LambdaMessage(
1507 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1508}
1509
1510void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1511 ATRACE_CALL();
1512
Ady Abraham27c70212019-06-11 10:52:26 -07001513 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1514
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001515 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001516 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1517 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001518 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001519 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001520 }
Mathias Agopian86303202012-07-24 22:46:10 -07001521}
1522
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001523// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001524void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001525 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526 // Clear the drawing state so that the logic inside of
1527 // handleTransactionLocked will fire. It will determine the delta between
1528 // mCurrentState and mDrawingState and re-apply all changes when we make the
1529 // transition.
1530 mDrawingState.displays.clear();
1531 mDisplays.clear();
1532}
1533
Steven Thomas050b2c82017-03-06 11:45:16 -08001534void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001535 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001536 if (!mVrFlinger)
1537 return;
1538 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001539 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001540 return;
1541 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542
Lloyd Pique441d5042018-10-18 16:49:51 -07001543 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 ALOGE("Vr flinger is only supported for remote hardware composer"
1545 " service connections. Ignoring request to transition to vr"
1546 " flinger.");
1547 mVrFlingerRequestsDisplay = false;
1548 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001549 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001550
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001552
Steven Thomas0123ac62018-07-12 11:32:34 -07001553 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001554 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001555
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001556 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001557
1558 // Clear out all the output layers from the composition engine for all
1559 // displays before destroying the hardware composer interface. This ensures
1560 // any HWC layers are destroyed through that interface before it becomes
1561 // invalid.
1562 for (const auto& [token, displayDevice] : mDisplays) {
1563 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1564 compositionengine::Output::OutputLayers());
1565 }
1566
Steven Thomas0123ac62018-07-12 11:32:34 -07001567 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1568 // called below. Clear the reference now so we don't accidentally use it
1569 // later.
1570 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001571
Steven Thomasb02664d2017-07-26 18:48:28 -07001572 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001573 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001574 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001575
Steven Thomasb02664d2017-07-26 18:48:28 -07001576 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001577 // Delete the current instance before creating the new one
1578 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1579 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1580 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1581 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001582
Lloyd Pique441d5042018-10-18 16:49:51 -07001583 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001584 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001585
1586 if (vrFlingerRequestsDisplay) {
1587 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001588 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001589
1590 mVisibleRegionsDirty = true;
1591 invalidateHwcGeometry();
1592
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001593 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001594 display = getDefaultDisplayDeviceLocked();
1595 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001596 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001597
Steven Thomasb02664d2017-07-26 18:48:28 -07001598 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001599 const nsecs_t vsyncPeriod = getVsyncPeriod();
1600 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001601
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001602 // The present fences returned from vr_hwc are not an accurate
1603 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001604 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001605
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 // Use phase of 0 since phase is not known.
1607 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001608 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001609 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001610
Ana Krulecc2870422019-01-29 19:00:58 -08001611 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001612
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001613 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001614 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001615}
1616
Ady Abrahamb40b0262019-09-19 11:32:43 -07001617bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1618 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001619 // We are storing the last 2 present fences. If sf's phase offset is to be
1620 // woken up before the actual vsync but targeting the next vsync, we need to check
1621 // fence N-2
1622 const sp<Fence>& fence =
1623 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1624 ? mPreviousPresentFences[0]
1625 : mPreviousPresentFences[1];
1626
Ady Abrahamb40b0262019-09-19 11:32:43 -07001627 if (fence == Fence::NO_FENCE) {
1628 return false;
1629 }
1630
1631 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1632 fence->wait(graceTimeMs);
1633 }
1634
1635 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001636}
1637
Ady Abraham7c03ce62019-07-19 10:59:45 -07001638void SurfaceFlinger::populateExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
Alec Mouriaa614192019-06-06 13:28:34 -07001639 DisplayStatInfo stats;
1640 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001641 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001642 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham7c03ce62019-07-19 10:59:45 -07001643 mExpectedPresentTime =
Alec Mouriaa614192019-06-06 13:28:34 -07001644 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1645 ? presentTime
1646 : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001647}
1648
Dominik Laskowski22488f62019-03-28 09:53:04 -07001649void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001650 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001651 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001652 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001653 // calculate the expected present time once and use the cached
1654 // value throughout this frame to make sure all layers are
1655 // seeing this same value.
1656 populateExpectedPresentTime();
1657
Ady Abrahamb40b0262019-09-19 11:32:43 -07001658 // When Backpressure propagation is enabled we want to give a small grace period
1659 // for the present fence to fire instead of just giving up on this frame to handle cases
1660 // where present fence is just about to get signaled.
1661 const int graceTimeForPresentFenceMs =
1662 (mPropagateBackpressure &&
1663 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1664 ? 1
1665 : 0;
1666 bool frameMissed = previousFrameMissed(graceTimeForPresentFenceMs);
Alec Mouricc0fc602019-02-26 21:45:19 -08001667 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1668 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1669 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1670 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1671 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1672 if (frameMissed) {
1673 mFrameMissedCount++;
1674 mTimeStats->incrementMissedFrames();
1675 }
1676
Alec Mouri40189b02019-03-05 15:07:54 -08001677 if (hwcFrameMissed) {
1678 mHwcFrameMissedCount++;
1679 }
1680
1681 if (gpuFrameMissed) {
1682 mGpuFrameMissedCount++;
1683 }
1684
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001685 if (mUseSmart90ForVideo) {
1686 // This call is made each time SF wakes up and creates a new frame. It is part
1687 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001688 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001689 }
1690
Ady Abrahamb838aed2019-02-12 15:30:16 -08001691 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001692 break;
1693 }
1694
Ady Abrahamadb9a992019-09-19 21:21:55 +00001695 if (frameMissed && mPropagateBackpressure) {
1696 if ((hwcFrameMissed && !gpuFrameMissed) ||
1697 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001698 signalLayerUpdate();
1699 break;
1700 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001701 }
Dan Stoza50182882016-07-08 12:02:20 -07001702
Steven Thomas050b2c82017-03-06 11:45:16 -08001703 // Now that we're going to make it to the handleMessageTransaction()
1704 // call below it's safe to call updateVrFlinger(), which will
1705 // potentially trigger a display handoff.
1706 updateVrFlinger();
1707
Dan Stoza6b9454d2014-11-07 16:00:59 -08001708 bool refreshNeeded = handleMessageTransaction();
1709 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001710
1711 updateCursorAsync();
1712 updateInputFlinger();
1713
Dan Stoza58784442014-12-02 16:58:17 -08001714 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001715 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001716 // Signal a refresh if a transaction modified the window state,
1717 // a new buffer was latched, or if HWC has requested a full
1718 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001719 signalRefresh();
1720 }
1721 break;
1722 }
1723 case MessageQueue::REFRESH: {
1724 handleMessageRefresh();
1725 break;
1726 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001727 }
1728}
1729
Dan Stoza6b9454d2014-11-07 16:00:59 -08001730bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001731 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001732 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001733
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001734 bool flushedATransaction = flushTransactionQueues();
1735
1736 bool runHandleTransaction = transactionFlags &&
1737 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1738
1739 if (runHandleTransaction) {
1740 handleTransaction(eTransactionMask);
1741 } else {
1742 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001743 }
1744
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001745 if (transactionFlushNeeded()) {
1746 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001747 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001748
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001749 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001750}
1751
Mathias Agopian4fec8732012-06-29 14:12:52 -07001752void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001754
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001755 mRefreshPending = false;
1756
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001757 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001758 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001759 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001760 calculateWorkingSet();
Nataniel Borgesc4def152019-09-26 15:20:00 +02001761 long compositionTime = elapsedRealtimeNano();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001762 for (const auto& [token, display] : mDisplays) {
1763 beginFrame(display);
1764 prepareFrame(display);
1765 doDebugFlashRegions(display, repaintEverything);
1766 doComposition(display, repaintEverything);
1767 }
1768
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001769 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001770
1771 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001772 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001773
Dan Stozabfbffeb2016-07-21 14:49:33 -07001774 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001775 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001776 for (const auto& [token, displayDevice] : mDisplays) {
1777 auto display = displayDevice->getCompositionDisplay();
1778 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001779 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001780 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001781 mHadDeviceComposition =
1782 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001783 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001784
Jorim Jaggi90535212018-05-23 23:44:06 +02001785 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001786
David Sodman7e4ae112018-02-09 15:02:28 -08001787 mLayersWithQueuedFrames.clear();
Vishnu Nair6bfe2642019-06-07 14:53:14 -07001788 if (mVisibleRegionsDirty) {
1789 mVisibleRegionsDirty = false;
1790 if (mTracingEnabled) {
Nataniel Borgesc4def152019-09-26 15:20:00 +02001791 mTracing.notify(compositionTime, "visibleRegionsDirty");
Vishnu Nair6bfe2642019-06-07 14:53:14 -07001792 }
1793 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001794}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001795
David Sodmanfa9b2af2017-12-24 13:28:59 -08001796
1797bool SurfaceFlinger::handleMessageInvalidate() {
1798 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001799 bool refreshNeeded = handlePageFlip();
1800
Vishnu Nair4351ad52019-02-11 14:13:02 -08001801 if (mVisibleRegionsDirty) {
1802 computeLayerBounds();
1803 }
1804
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001805 for (auto& layer : mLayersPendingRefresh) {
1806 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001807 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001808 invalidateLayerStack(layer, visibleReg);
1809 }
1810 mLayersPendingRefresh.clear();
1811 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001812}
1813
David Sodman79bba0e2018-08-05 18:07:49 -07001814void SurfaceFlinger::calculateWorkingSet() {
1815 ATRACE_CALL();
1816 ALOGV(__FUNCTION__);
1817
David Sodman79bba0e2018-08-05 18:07:49 -07001818 // build the h/w work list
1819 if (CC_UNLIKELY(mGeometryInvalid)) {
1820 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001821 for (const auto& [token, displayDevice] : mDisplays) {
1822 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001823
Lloyd Piquea83776c2019-01-29 18:42:32 -08001824 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001825
Lloyd Piquea83776c2019-01-29 18:42:32 -08001826 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1827 auto& compositionState = layer->editState();
1828 compositionState.forceClientComposition = false;
1829 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1830 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001831 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001832
Lloyd Piquea83776c2019-01-29 18:42:32 -08001833 // The output Z order is set here based on a simple counter.
1834 compositionState.z = zOrder++;
1835
1836 // Update the display independent composition state. This goes
1837 // to the general composition layer state structure.
1838 // TODO: Do this once per compositionengine::CompositionLayer.
1839 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1840 true);
1841
1842 // Recalculate the geometry state of the output layer.
1843 layer->updateCompositionState(true);
1844
1845 // Write the updated geometry state to the HWC
1846 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001847 }
1848 }
1849 }
1850
1851 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001852 for (const auto& [token, displayDevice] : mDisplays) {
1853 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001854 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001855 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001856 continue;
1857 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001858 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001859
1860 if (mDrawingState.colorMatrixChanged) {
1861 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001862 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001863 Dataspace targetDataspace = Dataspace::UNKNOWN;
1864 if (useColorManagement) {
1865 ColorMode colorMode;
1866 RenderIntent renderIntent;
1867 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1868 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001869
1870 if (isHdrColorMode(colorMode)) {
1871 targetDataspace = Dataspace::UNKNOWN;
1872 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1873 targetDataspace = mColorSpaceAgnosticDataspace;
1874 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001875 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001876
Lloyd Pique32cbe282018-10-19 13:09:22 -07001877 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001878 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001879 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001880 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1881 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001882 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001883 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001884 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1885 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001886 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001887 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001888 }
1889
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001890 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001891 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001892 }
1893
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001894 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001895 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001896 layer->setCompositionType(displayDevice,
1897 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001898 continue;
1899 }
1900
Lloyd Pique32cbe282018-10-19 13:09:22 -07001901 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001902 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001903 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001904 }
1905 }
1906
1907 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001908
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001909 for (const auto& [token, displayDevice] : mDisplays) {
1910 auto display = displayDevice->getCompositionDisplay();
1911 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001912 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1913 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1914 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001915 }
1916 }
David Sodman79bba0e2018-08-05 18:07:49 -07001917}
1918
Lloyd Pique32cbe282018-10-19 13:09:22 -07001919void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1920 bool repaintEverything) {
1921 auto display = displayDevice->getCompositionDisplay();
1922 const auto& displayState = display->getState();
1923
Mathias Agopiancd60f992012-08-16 16:28:27 -07001924 // is debugging enabled
1925 if (CC_LIKELY(!mDebugRegion))
1926 return;
1927
Lloyd Pique32cbe282018-10-19 13:09:22 -07001928 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001929 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001930 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001931 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001932 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001933 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001934 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001935
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001936 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001937 }
1938 }
1939
Lloyd Pique32cbe282018-10-19 13:09:22 -07001940 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001941
1942 if (mDebugRegion > 1) {
1943 usleep(mDebugRegion * 1000);
1944 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001945
Lloyd Pique32cbe282018-10-19 13:09:22 -07001946 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001947}
1948
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001949void SurfaceFlinger::logLayerStats() {
1950 ATRACE_CALL();
1951 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001952 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001953 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001954 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001955 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001956 }
1957 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001958
1959 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001960 }
1961}
1962
David Sodman2b406362017-12-15 13:33:47 -08001963void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001964{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001965 ATRACE_CALL();
1966 ALOGV("preComposition");
1967
David Sodman2b406362017-12-15 13:33:47 -08001968 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1969
Mathias Agopiancd60f992012-08-16 16:28:27 -07001970 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001971 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001972 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001973 needExtraInvalidate = true;
1974 }
Robert Carr2047fae2016-11-28 14:09:09 -08001975 });
1976
Mathias Agopiancd60f992012-08-16 16:28:27 -07001977 if (needExtraInvalidate) {
1978 signalLayerUpdate();
1979 }
1980}
1981
Ana Krulece588e312018-09-18 12:32:24 -07001982void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1983 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001984 // Update queue of past composite+present times and determine the
1985 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001986 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001987 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001988 while (!getBE().mCompositePresentTimes.empty()) {
1989 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990 // Cached values should have been updated before calling this method,
1991 // which helps avoid duplicate syscalls.
1992 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1993 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1994 break;
1995 }
1996 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001997 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001998 }
1999
2000 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002001 while (getBE().mCompositePresentTimes.size() > 16) {
2002 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002003 }
2004
Ana Krulece588e312018-09-18 12:32:24 -07002005 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002006}
2007
Ana Krulece588e312018-09-18 12:32:24 -07002008void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2009 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002010 // Integer division and modulo round toward 0 not -inf, so we need to
2011 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002012 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2013 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2014 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002015
Ana Krulec757f63a2019-01-25 10:46:18 -08002016 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002017 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002018 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002019 }
2020
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002021 // Snap the latency to a value that removes scheduling jitter from the
2022 // composition and present times, which often have >1ms of jitter.
2023 // Reducing jitter is important if an app attempts to extrapolate
2024 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002025 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002026 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002027 nsecs_t bias = stats.vsyncPeriod / 2;
2028 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2029 nsecs_t snappedCompositeToPresentLatency =
2030 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031
David Sodman99974d22017-11-28 12:04:33 -08002032 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002033 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2034 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002035 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002036}
2037
David Sodman2b406362017-12-15 13:33:47 -08002038void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002039{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002040 ATRACE_CALL();
2041 ALOGV("postComposition");
2042
Brian Anderson3546a3f2016-07-14 11:51:14 -07002043 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002044 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002045 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002046 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002047 }
2048
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002049 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002050 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002051
David Sodman73beded2017-11-15 11:56:06 -08002052 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002053 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002054 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002055 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002056 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2057 ->getRenderSurface()
2058 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002059 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002060 } else {
2061 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2062 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002063
David Sodman73beded2017-11-15 11:56:06 -08002064 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002065 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2066 mPreviousPresentFences[0] = displayDevice
2067 ? getHwComposer().getPresentFence(*displayDevice->getId())
2068 : Fence::NO_FENCE;
2069 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002070 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002071
Ana Krulece588e312018-09-18 12:32:24 -07002072 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002073 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002074
David Sodman2b406362017-12-15 13:33:47 -08002075 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002076 // when we started doing work for this frame, but that should be okay
2077 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002078 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002079 CompositorTiming compositorTiming;
2080 {
David Sodman99974d22017-11-28 12:04:33 -08002081 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2082 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002083 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002084
Robert Carr2047fae2016-11-28 14:09:09 -08002085 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002086 bool frameLatched =
2087 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2088 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002089 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002090 recordBufferingStats(layer->getName().string(),
2091 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002092 }
Robert Carr2047fae2016-11-28 14:09:09 -08002093 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002094
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002095 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002096 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002097 }
2098
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002099 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002100 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2101 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002102 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002103 }
2104 }
2105
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002106 if (mAnimCompositionPending) {
2107 mAnimCompositionPending = false;
2108
Brian Anderson4e606e32017-03-16 15:34:57 -07002109 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002110 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002111 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002112 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002113 // The HWC doesn't support present fences, so use the refresh
2114 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002115 const nsecs_t presentTime =
2116 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002117 mAnimFrameTracker.setActualPresentTime(presentTime);
2118 }
2119 mAnimFrameTracker.advanceFrame();
2120 }
Dan Stozab90cf072015-03-05 11:05:59 -08002121
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002122 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002123 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002124 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002125 }
2126
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002127 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002128
Lloyd Pique32cbe282018-10-19 13:09:22 -07002129 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2130 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002131 return;
2132 }
2133
2134 nsecs_t currentTime = systemTime();
2135 if (mHasPoweredOff) {
2136 mHasPoweredOff = false;
2137 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002138 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002139 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002140 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2141 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002142 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002143 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002144 }
David Sodman4a36e932017-11-07 14:29:47 -08002145 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002146 }
David Sodman4a36e932017-11-07 14:29:47 -08002147 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002148
2149 {
2150 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002151 if (mTexturePool.size() < mTexturePoolSize) {
2152 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002153 const size_t offset = mTexturePool.size();
2154 mTexturePool.resize(mTexturePoolSize);
2155 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2156 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002157 } else if (mTexturePool.size() > mTexturePoolSize) {
2158 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2159 const size_t offset = mTexturePoolSize;
2160 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2161 mTexturePool.resize(mTexturePoolSize);
2162 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002163 }
2164 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002165
Ady Abrahambe0f9482019-04-24 15:41:53 -07002166 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallf384e052019-06-12 13:25:07 -07002167
2168 // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
2169 // If we do not lock here, a callback could be sent without all of its SurfaceControls and
2170 // metrics.
2171 {
2172 Mutex::Autolock _l(mStateLock);
2173 mTransactionCompletedThread.sendCallbacks();
2174 }
Ady Abraham8164d482019-01-11 14:47:59 -08002175
Kevin DuBois413287f2019-02-25 08:46:47 -08002176 if (mLumaSampling && mRegionSamplingThread) {
2177 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002178 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002179
2180 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2181 // side-effect of getTotalSize(), so we check that again here
2182 if (ATRACE_ENABLED()) {
2183 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2184 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002185}
2186
Vishnu Nair4351ad52019-02-11 14:13:02 -08002187void SurfaceFlinger::computeLayerBounds() {
2188 for (const auto& pair : mDisplays) {
2189 const auto& displayDevice = pair.second;
2190 const auto display = displayDevice->getCompositionDisplay();
2191 for (const auto& layer : mDrawingState.layersSortedByZ) {
2192 // only consider the layers on the given layer stack
2193 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002194 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002195 }
2196
2197 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2198 }
2199 }
2200}
2201
Mathias Agopiancd60f992012-08-16 16:28:27 -07002202void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002203 ATRACE_CALL();
2204 ALOGV("rebuildLayerStacks");
2205
Mathias Agopiancd60f992012-08-16 16:28:27 -07002206 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002207 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002208 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002209 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002210
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002211 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002212 const auto& displayDevice = pair.second;
2213 auto display = displayDevice->getCompositionDisplay();
2214 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002215 Region opaqueRegion;
2216 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002217 compositionengine::Output::OutputLayers layersSortedByZ;
2218 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002219 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002220 const ui::Transform& tr = displayState.transform;
2221 const Rect bounds = displayState.bounds;
2222 if (displayState.isEnabled) {
2223 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002224
Jeff Sharkey76488112017-02-27 14:15:18 -07002225 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002226 auto compositionLayer = layer->getCompositionLayer();
2227 if (compositionLayer == nullptr) {
2228 return;
2229 }
2230
Lloyd Pique32cbe282018-10-19 13:09:22 -07002231 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002232 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2233 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2234
Lloyd Pique07e33212018-12-18 16:33:37 -08002235 bool needsOutputLayer = false;
2236
Lloyd Piqueef36b002019-01-23 17:52:04 -08002237 if (display->belongsInOutput(layer->getLayerStack(),
2238 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002239 Region drawRegion(tr.transform(
2240 layer->visibleNonTransparentRegion));
2241 drawRegion.andSelf(bounds);
2242 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002243 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002244 }
Chia-I Wu83806892017-11-16 10:50:20 -08002245 }
2246
Lloyd Pique07e33212018-12-18 16:33:37 -08002247 if (needsOutputLayer) {
2248 layersSortedByZ.emplace_back(
2249 display->getOrCreateOutputLayer(displayId, compositionLayer,
2250 layerFE));
2251 deprecated_layersSortedByZ.add(layer);
2252
2253 auto& outputLayerState = layersSortedByZ.back()->editState();
2254 outputLayerState.visibleRegion =
2255 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2256 } else if (displayId) {
2257 // For layers that are being removed from a HWC display,
2258 // and that have queued frames, add them to a a list of
2259 // released layers so we can properly set a fence.
2260 bool hasExistingOutputLayer =
2261 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2262 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2263 mLayersWithQueuedFrames.cend(),
2264 layer) != mLayersWithQueuedFrames.cend();
2265
2266 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002267 layersNeedingFences.add(layer);
2268 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002269 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002270 });
2271 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002272
2273 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2274
2275 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002276 displayDevice->setLayersNeedingFences(layersNeedingFences);
2277
2278 Region undefinedRegion{bounds};
2279 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2280
2281 display->editState().undefinedRegion = undefinedRegion;
2282 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002283 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002284 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002285}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002286
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002287// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002288// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002289// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002290// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002291// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002292// The returned HDR data space is one of
2293// - Dataspace::UNKNOWN
2294// - Dataspace::BT2020_HLG
2295// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002296Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2297 Dataspace* outHdrDataSpace,
2298 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002299 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002300 *outHdrDataSpace = Dataspace::UNKNOWN;
2301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002303 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002304 case Dataspace::V0_SCRGB:
2305 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002306 case Dataspace::BT2020:
2307 case Dataspace::BT2020_ITU:
2308 case Dataspace::BT2020_LINEAR:
2309 case Dataspace::DISPLAY_BT2020:
2310 bestDataSpace = Dataspace::DISPLAY_BT2020;
2311 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002312 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002313 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002314 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 case Dataspace::BT2020_PQ:
2316 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002317 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002318 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002319 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002320 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002321 case Dataspace::BT2020_HLG:
2322 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002323 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002324 // When there's mixed PQ content and HLG content, we set the HDR
2325 // data space to be BT2020_PQ and convert HLG to PQ.
2326 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2327 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002328 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002329 break;
2330 default:
2331 break;
2332 }
Romain Guy54f154a2017-10-24 21:40:32 +01002333 }
2334
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002335 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002336}
2337
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002338// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2340 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002341 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2342 *outMode = ColorMode::NATIVE;
2343 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002344 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002345 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002346 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002347
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002348 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002349 bool isHdrClientComposition = false;
2350 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002351
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002352 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2353
Peiyong Lina3ea5592019-02-10 14:45:00 -08002354 switch (mForceColorMode) {
2355 case ColorMode::SRGB:
2356 bestDataSpace = Dataspace::V0_SRGB;
2357 break;
2358 case ColorMode::DISPLAY_P3:
2359 bestDataSpace = Dataspace::DISPLAY_P3;
2360 break;
2361 default:
2362 break;
2363 }
2364
Peiyong Lindfde5112018-06-05 10:58:41 -07002365 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002366 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2367 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002368 if (isHdr) {
2369 bestDataSpace = hdrDataSpace;
2370 }
2371
Chia-I Wu0d711262018-05-21 15:19:35 -07002372 RenderIntent intent;
2373 switch (mDisplayColorSetting) {
2374 case DisplayColorSetting::MANAGED:
2375 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002376 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002377 break;
2378 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002379 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002380 break;
2381 default: // vendor display color setting
2382 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2383 break;
2384 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002385
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002386 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002387}
2388
Lloyd Pique32cbe282018-10-19 13:09:22 -07002389void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2390 auto display = displayDevice->getCompositionDisplay();
2391 const auto& displayState = display->getState();
2392
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002393 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002394 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2395 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002396
David Sodmanfa9b2af2017-12-24 13:28:59 -08002397 // If nothing has changed (!dirty), don't recompose.
2398 // If something changed, but we don't currently have any visible layers,
2399 // and didn't when we last did a composition, then skip it this time.
2400 // The second rule does two things:
2401 // - When all layers are removed from a display, we'll emit one black
2402 // frame, then nothing more until we get new layers.
2403 // - When a display is created with a private layer stack, we won't
2404 // emit any black frames until a layer is added to the layer stack.
2405 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002406
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 const char flagPrefix[] = {'-', '+'};
2408 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002409 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2410 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2411 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2412 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002413
Lloyd Pique31cb2942018-10-19 17:23:03 -07002414 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002415
David Sodmanfa9b2af2017-12-24 13:28:59 -08002416 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002417 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002418 }
2419}
2420
Lloyd Pique32cbe282018-10-19 13:09:22 -07002421void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2422 auto display = displayDevice->getCompositionDisplay();
2423 const auto& displayState = display->getState();
2424
2425 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002426 return;
David Sodman2b406362017-12-15 13:33:47 -08002427 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002428
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002429 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002432}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002433
Lloyd Pique32cbe282018-10-19 13:09:22 -07002434void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002435 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002436 ALOGV("doComposition");
2437
Lloyd Pique32cbe282018-10-19 13:09:22 -07002438 auto display = displayDevice->getCompositionDisplay();
2439 const auto& displayState = display->getState();
2440
2441 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002442 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002443 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002444
David Sodmanfa9b2af2017-12-24 13:28:59 -08002445 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002446 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002447
Lloyd Pique32cbe282018-10-19 13:09:22 -07002448 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002449 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002450 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002451 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002452}
2453
David Sodmanfa9b2af2017-12-24 13:28:59 -08002454void SurfaceFlinger::postFrame()
2455{
2456 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002457 const auto display = getDefaultDisplayDeviceLocked();
2458 if (display && getHwComposer().isConnected(*display->getId())) {
2459 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002460 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2461 logFrameStats();
2462 }
2463 }
2464}
2465
Lloyd Pique32cbe282018-10-19 13:09:22 -07002466void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002467 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002468 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002469
Lloyd Pique32cbe282018-10-19 13:09:22 -07002470 auto display = displayDevice->getCompositionDisplay();
2471 const auto& displayState = display->getState();
2472 const auto displayId = display->getId();
2473
Lloyd Pique32cbe282018-10-19 13:09:22 -07002474 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002475 if (displayId) {
2476 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002477 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002478 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002479 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002480 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002481 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002482
Chia-I Wu7b549592017-11-15 09:14:57 -08002483 // The layer buffer from the previous frame (if any) is released
2484 // by HWC only when the release fence from this frame (if any) is
2485 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002486 if (layer->getState().hwc) {
2487 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002488 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002489 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2490 usedClientComposition =
2491 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002492 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002493
2494 // If the layer was client composited in the previous frame, we
2495 // need to merge with the previous client target acquire fence.
2496 // Since we do not track that, always merge with the current
2497 // client target acquire fence when it is available, even though
2498 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002499 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002500 releaseFence =
2501 Fence::merge("LayerRelease", releaseFence,
2502 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002503 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002504
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002505 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002506 }
Chia-I Wu83806892017-11-16 10:50:20 -08002507
2508 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002510 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002511 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002512 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002513 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002514 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002515 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002516 }
2517 }
2518
Dominik Laskowski075d3172018-05-24 15:50:06 -07002519 if (displayId) {
2520 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002521 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002522 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523}
2524
Mathias Agopian87baae12012-07-31 12:38:26 -07002525void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526{
Mathias Agopian841cde52012-03-01 15:44:37 -08002527 ATRACE_CALL();
2528
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002529 // here we keep a copy of the drawing state (that is the state that's
2530 // going to be overwritten by handleTransactionLocked()) outside of
2531 // mStateLock so that the side-effects of the State assignment
2532 // don't happen with mStateLock held (which can cause deadlocks).
2533 State drawingState(mDrawingState);
2534
Mathias Agopianca4d3602011-05-19 15:38:14 -07002535 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002536 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002537
Mathias Agopianca4d3602011-05-19 15:38:14 -07002538 // Here we're guaranteed that some transaction flags are set
2539 // so we can call handleTransactionLocked() unconditionally.
2540 // We call getTransactionFlags(), which will also clear the flags,
2541 // with mStateLock held to guarantee that mCurrentState won't change
2542 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002543
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002544 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002545 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002546 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002547
Mathias Agopianca4d3602011-05-19 15:38:14 -07002548 mDebugInTransaction = 0;
2549 invalidateHwcGeometry();
2550 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002551}
2552
Lloyd Piqueba04e622017-12-14 17:11:26 -08002553void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2554 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002555 const std::optional<DisplayIdentificationInfo> info =
2556 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002557
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002559 continue;
2560 }
2561
Lloyd Piqueba04e622017-12-14 17:11:26 -08002562 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002563 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002564 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomase9eb1832019-08-28 16:08:35 -07002565 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2566 initScheduler(info->id);
2567 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002568 mPhysicalDisplayTokens[info->id] = new BBinder();
2569 DisplayDeviceState state;
2570 state.displayId = info->id;
2571 state.isSecure = true; // All physical displays are currently considered secure.
2572 state.displayName = info->name;
2573 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2574 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002575 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002576 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002577 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002578
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2580 if (index >= 0) {
2581 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2582 mInterceptor->saveDisplayDeletion(state.sequenceId);
2583 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002584 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002585 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002586 }
2587
2588 processDisplayChangesLocked();
2589 }
2590
2591 mPendingHotplugEvents.clear();
2592}
2593
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002594void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002595 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2596 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002597}
2598
Lloyd Pique99d3da52018-01-22 17:48:03 -08002599sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002600 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002601 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002602 const sp<IGraphicBufferProducer>& producer) {
2603 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002604 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002606 creationArgs.isSecure = state.isSecure;
2607 creationArgs.displaySurface = dispSurface;
2608 creationArgs.hasWideColorGamut = false;
2609 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002610
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002611 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002612 creationArgs.isPrimary = isInternalDisplay;
2613
2614 if (useColorManagement && displayId) {
2615 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002616 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002617 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002618 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002619 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002620
Dominik Laskowski7e045462018-05-30 13:02:02 -07002621 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002623 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002624 }
tangrobin6753a022018-08-10 10:58:54 +08002625 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002626
Dominik Laskowski075d3172018-05-24 15:50:06 -07002627 if (displayId) {
2628 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002629 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002631 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002632
Lloyd Pique90c115d2018-09-18 21:39:42 -07002633 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002634 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002635 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002636
Lloyd Pique99d3da52018-01-22 17:48:03 -08002637 // Make sure that composition can never be stalled by a virtual display
2638 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002639 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002640 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002641 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2642 }
2643
Dominik Laskowski075d3172018-05-24 15:50:06 -07002644 creationArgs.displayInstallOrientation =
2645 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002646
Lloyd Pique99d3da52018-01-22 17:48:03 -08002647 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002648 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002649
Lloyd Pique90c115d2018-09-18 21:39:42 -07002650 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002651
2652 if (maxFrameBufferAcquiredBuffers >= 3) {
2653 nativeWindowSurface->preallocateBuffers();
2654 }
2655
2656 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002657 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002658 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002659 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002660 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002661 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002662 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2663 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 if (!state.isVirtual()) {
2665 LOG_ALWAYS_FATAL_IF(!displayId);
2666 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002667 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002668
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002669 display->setLayerStack(state.layerStack);
2670 display->setProjection(state.orientation, state.viewport, state.frame);
2671 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002672
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002673 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002674}
2675
Lloyd Pique347200f2017-12-14 17:00:15 -08002676void SurfaceFlinger::processDisplayChangesLocked() {
2677 // here we take advantage of Vector's copy-on-write semantics to
2678 // improve performance by skipping the transaction entirely when
2679 // know that the lists are identical
2680 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2681 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2682 if (!curr.isIdenticalTo(draw)) {
2683 mVisibleRegionsDirty = true;
2684 const size_t cc = curr.size();
2685 size_t dc = draw.size();
2686
2687 // find the displays that were removed
2688 // (ie: in drawing state but not in current state)
2689 // also handle displays that changed
2690 // (ie: displays that are in both lists)
2691 for (size_t i = 0; i < dc;) {
2692 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2693 if (j < 0) {
2694 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002695 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002696 // Save display ID before disconnecting.
2697 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002698 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002699
2700 if (!display->isVirtual()) {
2701 LOG_ALWAYS_FATAL_IF(!displayId);
2702 dispatchDisplayHotplugEvent(displayId->value, false);
2703 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002705
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002707 } else {
2708 // this display is in both lists. see if something changed.
2709 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002711 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2712 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2713 if (state_binder != draw_binder) {
2714 // changing the surface is like destroying and
2715 // recreating the DisplayDevice, so we just remove it
2716 // from the drawing state, so that it get re-added
2717 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002718 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002719 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002720 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002721 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002722 mDrawingState.displays.removeItemsAt(i);
2723 dc--;
2724 // at this point we must loop to the next item
2725 continue;
2726 }
2727
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002728 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002729 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002730 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002731 }
2732 if ((state.orientation != draw[i].orientation) ||
2733 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002735 }
2736 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002738 }
2739 }
2740 }
2741 ++i;
2742 }
2743
2744 // find displays that were added
2745 // (ie: in current state but not in drawing state)
2746 for (size_t i = 0; i < cc; i++) {
2747 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2748 const DisplayDeviceState& state(curr[i]);
2749
Lloyd Pique542307f2018-10-19 13:24:08 -07002750 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002751 sp<IGraphicBufferProducer> producer;
2752 sp<IGraphicBufferProducer> bqProducer;
2753 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002754 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002755
Dominik Laskowski075d3172018-05-24 15:50:06 -07002756 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002757 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002758 // Virtual displays without a surface are dormant:
2759 // they have external state (layer stack, projection,
2760 // etc.) but no internal state (i.e. a DisplayDevice).
2761 if (state.surface != nullptr) {
2762 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002763 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002764 int width = 0;
2765 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2766 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2767 int height = 0;
2768 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2769 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2770 int intFormat = 0;
2771 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2772 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002773 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002774
Dominik Laskowski075d3172018-05-24 15:50:06 -07002775 displayId =
2776 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 }
2778
2779 // TODO: Plumb requested format back up to consumer
2780
2781 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002782 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002783 bqProducer, bqConsumer,
2784 state.displayName);
2785
2786 dispSurface = vds;
2787 producer = vds;
2788 }
2789 } else {
2790 ALOGE_IF(state.surface != nullptr,
2791 "adding a supported display, but rendering "
2792 "surface is provided (%p), ignoring it",
2793 state.surface.get());
2794
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 displayId = state.displayId;
2796 LOG_ALWAYS_FATAL_IF(!displayId);
2797 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002798 producer = bqProducer;
2799 }
2800
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002801 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002802 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002803 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002804 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002805 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002806 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002807 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002808 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002809 }
2810 }
2811 }
2812 }
2813 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002814
2815 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002816}
2817
Mathias Agopian87baae12012-07-31 12:38:26 -07002818void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002819{
Dan Stoza7dde5992015-05-22 09:51:44 -07002820 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002821 mCurrentState.traverseInZOrder([](Layer* layer) {
2822 layer->notifyAvailableFrames();
2823 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002824
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002825 /*
2826 * Traversal of the children
2827 * (perform the transaction for each of them if needed)
2828 */
2829
Marissa Wall06255332019-03-27 13:48:27 -07002830 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002832 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002833 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834
2835 const uint32_t flags = layer->doTransaction(0);
2836 if (flags & Layer::eVisibleRegion)
2837 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002838
2839 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002840 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002841 }
Robert Carr2047fae2016-11-28 14:09:09 -08002842 });
Marissa Wall06255332019-03-27 13:48:27 -07002843 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002844 }
2845
2846 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002847 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002848 */
2849
Mathias Agopiane57f2922012-08-09 16:29:12 -07002850 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002851 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002852 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002853 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002854
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002855 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002856 // The transform hint might have changed for some layers
2857 // (either because a display has changed, or because a layer
2858 // as changed).
2859 //
2860 // Walk through all the layers in currentLayers,
2861 // and update their transform hint.
2862 //
2863 // If a layer is visible only on a single display, then that
2864 // display is used to calculate the hint, otherwise we use the
2865 // default display.
2866 //
2867 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2868 // the hint is set before we acquire a buffer from the surface texture.
2869 //
2870 // NOTE: layer transactions have taken place already, so we use their
2871 // drawing state. However, SurfaceFlinger's own transaction has not
2872 // happened yet, so we must use the current state layer list
2873 // (soon to become the drawing state list).
2874 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002875 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002876 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002877 bool first = true;
2878 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002879 // NOTE: we rely on the fact that layers are sorted by
2880 // layerStack first (so we don't have to traverse the list
2881 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002882 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002883 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002884 currentlayerStack = layerStack;
2885 // figure out if this layerstack is mirrored
2886 // (more than one display) if so, pick the default display,
2887 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002888 hintDisplay = nullptr;
2889 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002890 if (display->getCompositionDisplay()
2891 ->belongsInOutput(layer->getLayerStack(),
2892 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002893 if (hintDisplay) {
2894 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002895 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002896 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002897 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002898 }
2899 }
2900 }
2901 }
Chet Haase91d25932013-04-11 15:24:55 -07002902
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002903 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002904 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2905 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002906
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002907 // could be null when this layer is using a layerStack
2908 // that is not visible on any display. Also can occur at
2909 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002910 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002911 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002912
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002913 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002914 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002915 if (hintDisplay) {
2916 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002917 }
Robert Carr2047fae2016-11-28 14:09:09 -08002918
2919 first = false;
2920 });
Mathias Agopian84300952012-11-21 16:02:13 -08002921 }
2922
2923
Mathias Agopian3559b072012-08-15 13:46:03 -07002924 /*
2925 * Perform our own transaction if needed
2926 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002927
2928 if (mLayersAdded) {
2929 mLayersAdded = false;
2930 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002931 mVisibleRegionsDirty = true;
2932 }
2933
2934 // some layers might have been removed, so
2935 // we need to update the regions they're exposing.
2936 if (mLayersRemoved) {
2937 mLayersRemoved = false;
2938 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002939 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002940 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002941 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002942 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002943 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002944 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002945 }
Robert Carr2047fae2016-11-28 14:09:09 -08002946 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002947 }
2948
Vishnu Nairec0ab382019-02-13 15:32:56 -08002949 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002951}
2952
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002953void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002954 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002955 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002956 return;
2957 }
2958
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002959 if (mVisibleRegionsDirty || mInputInfoChanged) {
2960 mInputInfoChanged = false;
2961 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002962 } else if (mInputWindowCommands.syncInputWindows) {
2963 // If the caller requested to sync input windows, but there are no
2964 // changes to input windows, notify immediately.
2965 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002966 }
2967
Arthur Hung5845eaf2019-09-05 16:38:18 +08002968 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002969}
2970
2971void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002972 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002973
2974 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2975 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002976 // When calculating the screen bounds we ignore the transparent region since it may
2977 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002978 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002979 }
2980 });
chaviw291d88a2019-02-14 10:33:58 -08002981
2982 mInputFlinger->setInputWindows(inputHandles,
2983 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2984 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002985}
2986
Vishnu Nairec0ab382019-02-13 15:32:56 -08002987void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002988 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002989 mPendingInputWindowCommands.clear();
2990}
2991
Riley Andrews03414a12014-07-01 14:22:59 -07002992void SurfaceFlinger::updateCursorAsync()
2993{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002994 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002995 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002996 continue;
2997 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002998
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002999 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3000 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003001 }
3002 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003003}
3004
chaviw61626f22018-11-15 16:26:27 -08003005void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3006 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003007 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003008 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003009 }
3010 layer->releasePendingBuffer(systemTime());
3011}
3012
Steven Thomase9eb1832019-08-28 16:08:35 -07003013void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
3014 if (mScheduler) {
3015 // In practice it's not allowed to hotplug in/out the primary display once it's been
3016 // connected during startup, but some tests do it, so just warn and return.
3017 ALOGW("Can't re-init scheduler");
3018 return;
3019 }
3020
3021 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
3022 mRefreshRateConfigs =
3023 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
3024 getHwComposer().getConfigs(
3025 primaryDisplayId),
3026 currentConfig);
3027 mRefreshRateStats =
3028 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
3029 currentConfig, HWC_POWER_MODE_OFF);
3030 mRefreshRateStats->setConfigMode(currentConfig);
3031
3032 // start the EventThread
3033 mScheduler =
3034 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
3035 *mRefreshRateConfigs);
3036 mAppConnectionHandle =
3037 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
3038 mPhaseOffsets->getOffsetThresholdForNextVsync(),
3039 impl::EventThread::InterceptVSyncsCallback());
3040 mSfConnectionHandle =
3041 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
3042 mPhaseOffsets->getOffsetThresholdForNextVsync(),
3043 [this](nsecs_t timestamp) {
3044 mInterceptor->saveVSyncEvent(timestamp);
3045 });
3046
3047 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
3048 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
3049 mSfConnectionHandle.get());
3050
3051 mRegionSamplingThread =
3052 new RegionSamplingThread(*this, *mScheduler,
3053 RegionSamplingThread::EnvironmentTimingTunables());
3054
3055 mScheduler->setChangeRefreshRateCallback(
3056 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
3057 Mutex::Autolock lock(mStateLock);
3058 setRefreshRateTo(type, event);
3059 });
3060}
3061
Mathias Agopian4fec8732012-06-29 14:12:52 -07003062void SurfaceFlinger::commitTransaction()
3063{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003064 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003066 for (const auto& l : mLayersPendingRemoval) {
3067 recordBufferingStats(l->getName().string(),
3068 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003069
Lloyd Pique07e33212018-12-18 16:33:37 -08003070 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003071 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003072 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003073 }
chaviw74d90ad2019-04-26 14:45:26 -07003074
3075 // If the layer has been removed and has no parent, then it will not be reachable
3076 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3077 // ensure we can copy its current to drawing state.
3078 if (!l->getParent()) {
3079 mOffscreenLayers.emplace(l.get());
3080 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003081 }
3082 mLayersPendingRemoval.clear();
3083 }
3084
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003085 // If this transaction is part of a window animation then the next frame
3086 // we composite should be considered an animation as well.
3087 mAnimCompositionPending = mAnimTransactionPending;
3088
Nataniel Borges2b796da2019-02-15 13:32:18 -08003089 withTracingLock([&]() {
3090 mDrawingState = mCurrentState;
3091 // clear the "changed" flags in current state
3092 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003093
chaviw74d90ad2019-04-26 14:45:26 -07003094 mDrawingState.traverseInZOrder([&](Layer* layer) {
3095 layer->commitChildList();
3096
3097 // If the layer can be reached when traversing mDrawingState, then the layer is no
3098 // longer offscreen. Remove the layer from the offscreenLayer set.
3099 if (mOffscreenLayers.count(layer)) {
3100 mOffscreenLayers.erase(layer);
3101 }
3102 });
3103
3104 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003105 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003106
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003107 mTransactionPending = false;
3108 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003109 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110}
3111
Nataniel Borges2b796da2019-02-15 13:32:18 -08003112void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3113 if (mTracingEnabledChanged) {
3114 mTracingEnabled = mTracing.isEnabled();
3115 mTracingEnabledChanged = false;
3116 }
3117
3118 // Synchronize with Tracing thread
3119 std::unique_lock<std::mutex> lock;
3120 if (mTracingEnabled) {
3121 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3122 }
3123
3124 lockedOperation();
3125
3126 // Synchronize with Tracing thread
3127 if (mTracingEnabled) {
3128 lock.unlock();
3129 }
3130}
3131
chaviw74d90ad2019-04-26 14:45:26 -07003132void SurfaceFlinger::commitOffscreenLayers() {
3133 for (Layer* offscreenLayer : mOffscreenLayers) {
3134 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3135 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3136 if (!trFlags) return;
3137
3138 layer->doTransaction(0);
3139 layer->commitChildList();
3140 });
3141 }
3142}
3143
Lloyd Pique32cbe282018-10-19 13:09:22 -07003144void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003145 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003146 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003147 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003148
Lloyd Pique32cbe282018-10-19 13:09:22 -07003149 auto display = displayDevice->getCompositionDisplay();
3150
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003151 Region aboveOpaqueLayers;
3152 Region aboveCoveredLayers;
3153 Region dirty;
3154
Mathias Agopian87baae12012-07-31 12:38:26 -07003155 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156
Robert Carr2047fae2016-11-28 14:09:09 -08003157 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003158 // start with the whole surface at its current location
3159 const Layer::State& s(layer->getDrawingState());
3160
Jesse Hall01e29052013-02-19 16:13:35 -08003161 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003162 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003163 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003164 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003165
Mathias Agopianab028732010-03-16 16:41:46 -07003166 /*
3167 * opaqueRegion: area of a surface that is fully opaque.
3168 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003169 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003170
3171 /*
3172 * visibleRegion: area of a surface that is visible on screen
3173 * and not fully transparent. This is essentially the layer's
3174 * footprint minus the opaque regions above it.
3175 * Areas covered by a translucent surface are considered visible.
3176 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003177 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003178
3179 /*
3180 * coveredRegion: area of a surface that is covered by all
3181 * visible regions above it (which includes the translucent areas).
3182 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003184
Jesse Halla8026d22012-09-25 13:25:04 -07003185 /*
3186 * transparentRegion: area of a surface that is hinted to be completely
3187 * transparent. This is only used to tell when the layer has no visible
3188 * non-transparent regions and can be removed from the layer list. It
3189 * does not affect the visibleRegion of this layer or any layers
3190 * beneath it. The hint may not be correct if apps don't respect the
3191 * SurfaceView restrictions (which, sadly, some don't).
3192 */
3193 Region transparentRegion;
3194
Mathias Agopianab028732010-03-16 16:41:46 -07003195
3196 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003197 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003198 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003199 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003201 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003202 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003203 if (!visibleRegion.isEmpty()) {
3204 // Remove the transparent area from the visible region
3205 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003206 if (tr.preserveRects()) {
3207 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003208 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003209 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003210 // transformation too complex, can't do the
3211 // transparent region optimization.
3212 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003213 }
Mathias Agopianab028732010-03-16 16:41:46 -07003214 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003215
Mathias Agopianab028732010-03-16 16:41:46 -07003216 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003217 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003218 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003219 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003220 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003221 // the opaque region is the layer's footprint
3222 opaqueRegion = visibleRegion;
3223 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 }
3225 }
3226
Robert Carre5f4f692018-01-12 13:12:28 -08003227 if (visibleRegion.isEmpty()) {
3228 layer->clearVisibilityRegions();
3229 return;
3230 }
3231
Mathias Agopianab028732010-03-16 16:41:46 -07003232 // Clip the covered region to the visible region
3233 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3234
3235 // Update aboveCoveredLayers for next (lower) layer
3236 aboveCoveredLayers.orSelf(visibleRegion);
3237
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 // subtract the opaque region covered by the layers above us
3239 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240
3241 // compute this layer's dirty region
3242 if (layer->contentDirty) {
3243 // we need to invalidate the whole region
3244 dirty = visibleRegion;
3245 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003246 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003247 layer->contentDirty = false;
3248 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003249 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003250 * the exposed region consists of two components:
3251 * 1) what's VISIBLE now and was COVERED before
3252 * 2) what's EXPOSED now less what was EXPOSED before
3253 *
3254 * note that (1) is conservative, we start with the whole
3255 * visible region but only keep what used to be covered by
3256 * something -- which mean it may have been exposed.
3257 *
3258 * (2) handles areas that were not covered by anything but got
3259 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003260 */
Mathias Agopianab028732010-03-16 16:41:46 -07003261 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003262 const Region oldVisibleRegion = layer->visibleRegion;
3263 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003264 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3265 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003266 }
3267 dirty.subtractSelf(aboveOpaqueLayers);
3268
3269 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003270 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003271
Mathias Agopianab028732010-03-16 16:41:46 -07003272 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003273 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003274
Jesse Halla8026d22012-09-25 13:25:04 -07003275 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276 layer->setVisibleRegion(visibleRegion);
3277 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003278 layer->setVisibleNonTransparentRegion(
3279 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003280 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281
Mathias Agopian87baae12012-07-31 12:38:26 -07003282 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003283}
3284
Chia-I Wuab0c3192017-08-01 11:29:00 -07003285void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003286 for (const auto& [token, displayDevice] : mDisplays) {
3287 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003288 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003289 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003290 }
3291 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003292}
3293
Dan Stoza6b9454d2014-11-07 16:00:59 -08003294bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295{
Ady Abraham09bd3922019-04-08 10:44:56 -07003296 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003297 ALOGV("handlePageFlip");
3298
Brian Andersond6927fb2016-07-23 23:37:30 -07003299 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003300
Mathias Agopian4fec8732012-06-29 14:12:52 -07003301 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003302 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003303 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003304
3305 // Store the set of layers that need updates. This set must not change as
3306 // buffers are being latched, as this could result in a deadlock.
3307 // Example: Two producers share the same command stream and:
3308 // 1.) Layer 0 is latched
3309 // 2.) Layer 0 gets a new frame
3310 // 2.) Layer 1 gets a new frame
3311 // 3.) Layer 1 is latched.
3312 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3313 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003314 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003315 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003316 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003317 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003318 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003319 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003320 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003321 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003322 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003323 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003324 } else {
3325 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003326 }
Robert Carr2047fae2016-11-28 14:09:09 -08003327 });
3328
Lloyd Piquef2c79392018-12-20 16:23:33 -08003329 if (!mLayersWithQueuedFrames.empty()) {
3330 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3331 // writes to Layer current state. See also b/119481871
3332 Mutex::Autolock lock(mStateLock);
3333
3334 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003335 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003336 mLayersPendingRefresh.push_back(layer);
3337 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003338 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003339 if (layer->isBufferLatched()) {
3340 newDataLatched = true;
3341 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003342 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003343 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003344
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003345 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003346
3347 // If we will need to wake up at some time in the future to deal with a
3348 // queued frame that shouldn't be displayed during this vsync period, wake
3349 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003350 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003351 signalLayerUpdate();
3352 }
3353
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003354 // enter boot animation on first buffer latch
3355 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3356 ALOGI("Enter boot animation");
3357 mBootStage = BootStage::BOOTANIMATION;
3358 }
3359
Dan Stoza6b9454d2014-11-07 16:00:59 -08003360 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003361 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003362}
3363
Mathias Agopianad456f92011-01-13 17:53:01 -08003364void SurfaceFlinger::invalidateHwcGeometry()
3365{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003366 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003367}
3368
Lloyd Pique32cbe282018-10-19 13:09:22 -07003369void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003370 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003371 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003372 // We only need to actually compose the display if:
3373 // 1) It is being handled by hardware composer, which may need this to
3374 // keep its virtual display state machine in sync, or
3375 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003376 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003377 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003378 return;
3379 }
3380
Dan Stoza9e56aa02015-11-02 13:00:03 -08003381 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003382 base::unique_fd readyFence;
3383 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003384
3385 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003386 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003387}
3388
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003389bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3390 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003391 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003392 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003393
Lloyd Pique32cbe282018-10-19 13:09:22 -07003394 auto display = displayDevice->getCompositionDisplay();
3395 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003396 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003397 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003398 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003399
3400 const Region bounds(displayState.bounds);
3401 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003402 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003403 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003404
Chia-I Wu8e50e692018-05-04 10:12:37 -07003405 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003406
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003407 renderengine::DisplaySettings clientCompositionDisplay;
3408 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3409 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003410 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003411
Dan Stoza9e56aa02015-11-02 13:00:03 -08003412 if (hasClientComposition) {
3413 ALOGV("hasClientComposition");
3414
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003415 if (displayDevice->isPrimary() && supportProtectedContent) {
3416 bool needsProtected = false;
3417 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3418 // If the layer is a protected layer, mark protected context is needed.
3419 if (layer->isProtected()) {
3420 needsProtected = true;
3421 break;
3422 }
3423 }
Peiyong Lin52010312019-05-02 14:22:16 -07003424 if (needsProtected != renderEngine.isProtected()) {
3425 renderEngine.useProtectedContext(needsProtected);
3426 }
3427 if (needsProtected != display->getRenderSurface()->isProtected() &&
3428 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003429 display->getRenderSurface()->setProtected(needsProtected);
3430 }
3431 }
3432
Alec Mouri6338c9d2019-02-07 16:57:51 -08003433 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003434
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003435 if (buf == nullptr) {
3436 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3437 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003438 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003439 return false;
3440 }
3441
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003442 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3443 clientCompositionDisplay.clip = displayState.scissor;
3444 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003445 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003446 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003447
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003448 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003449 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003450 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003451 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003452 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003453 clientCompositionDisplay.outputDataspace = outputDataspace;
3454 clientCompositionDisplay.maxLuminance =
3455 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003456
Lloyd Pique441d5042018-10-18 16:49:51 -07003457 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003458 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003459 getHwComposer()
3460 .hasDisplayCapability(displayId,
3461 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003462
Peiyong Lind3788632018-09-18 16:01:31 -07003463 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003464 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3465 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003466 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003467 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003468 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003469
Mathias Agopian85d751c2012-08-29 16:59:24 -07003470 /*
3471 * and then, render the layers targeted at the framebuffer
3472 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003473
Dan Stoza9e56aa02015-11-02 13:00:03 -08003474 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003475 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003476 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003477 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003478 const Region viewportRegion(displayState.viewport);
3479 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003480 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003481 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003482 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003483 switch (layer->getCompositionType(displayDevice)) {
3484 case Hwc2::IComposerClient::Composition::CURSOR:
3485 case Hwc2::IComposerClient::Composition::DEVICE:
3486 case Hwc2::IComposerClient::Composition::SIDEBAND:
3487 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003488 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003489 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003490 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003491 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003492 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003493 // never clear the very first layer since we're
3494 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003495 renderengine::LayerSettings layerSettings;
3496 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003497 bool prepared =
3498 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3499 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003500
3501 if (prepared) {
3502 layerSettings.source.buffer.buffer = nullptr;
3503 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3504 layerSettings.alpha = half(0.0);
3505 layerSettings.disableBlending = true;
3506 clientCompositionLayers.push_back(layerSettings);
3507 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003508 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003509 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003510 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003511 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003512 renderengine::LayerSettings layerSettings;
3513 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003514 layer->prepareClientLayer(renderArea, clip, clearRegion,
3515 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003516 if (prepared) {
3517 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003518 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003519 break;
3520 }
3521 default:
3522 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003523 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003524 } else {
3525 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003526 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003527 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003528 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003529
Alec Mouri820c7402019-01-23 13:02:39 -08003530 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003531 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003532 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003533
3534 // We boost GPU frequency here because there will be color spaces conversion
3535 // and it's expensive. We boost the GPU frequency so that GPU composition can
3536 // finish in time. We must reset GPU frequency afterwards, because high frequency
3537 // consumes extra battery.
3538 const bool expensiveRenderingExpected =
3539 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3540 if (expensiveRenderingExpected && displayId) {
3541 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3542 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003543 if (!debugRegion.isEmpty()) {
3544 Region::const_iterator it = debugRegion.begin();
3545 Region::const_iterator end = debugRegion.end();
3546 while (it != end) {
3547 const Rect& rect = *it++;
3548 renderengine::LayerSettings layerSettings;
3549 layerSettings.source.buffer.buffer = nullptr;
3550 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3551 layerSettings.geometry.boundaries = rect.toFloatRect();
3552 layerSettings.alpha = half(1.0);
3553 clientCompositionLayers.push_back(layerSettings);
3554 }
3555 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003556 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003557 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3558 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003559 } else if (displayId) {
3560 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003561 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003562 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563}
3564
Chia-I Wu28e3a252018-09-07 12:05:02 -07003565void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003566 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003567 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003568}
3569
Robert Carrc0df3122019-04-11 13:18:21 -07003570status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3571 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3572 const sp<IBinder>& parentHandle,
3573 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003574 // add this layer to the current state list
3575 {
3576 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003577 sp<Layer> parent;
3578 if (parentHandle != nullptr) {
3579 parent = fromHandle(parentHandle);
3580 if (parent == nullptr) {
3581 return NAME_NOT_FOUND;
3582 }
3583 } else {
3584 parent = parentLayer;
3585 }
3586
Robert Carr1f0a16a2016-10-24 16:27:39 -07003587 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003588 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3589 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003590 return NO_MEMORY;
3591 }
Robert Carrc0df3122019-04-11 13:18:21 -07003592
3593 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3594
Robert Carrb89ea9d2018-12-10 13:01:14 -08003595 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003596 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003597 } else if (parent == nullptr) {
3598 lbc->onRemovedFromCurrentState();
3599 } else if (parent->isRemovedFromCurrentState()) {
3600 parent->addChild(lbc);
3601 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003602 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003603 parent->addChild(lbc);
3604 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003605
Yiwei Zhang243b3782018-05-15 17:40:04 -07003606 if (gbc != nullptr) {
3607 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3608 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3609 mMaxGraphicBufferProducerListSize,
3610 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3611 mGraphicBufferProducerList.size(),
3612 mMaxGraphicBufferProducerListSize, mNumLayers);
3613 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003614 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003615 }
3616
Mathias Agopian96f08192010-06-02 23:28:45 -07003617 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003618 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003619
Dan Stoza7d89d062015-04-30 13:29:25 -07003620 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003621}
3622
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003623uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003624 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003625}
3626
Mathias Agopian3f844832013-08-07 21:24:32 -07003627uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003628 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003629}
3630
Mathias Agopian3f844832013-08-07 21:24:32 -07003631uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003632 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003633}
3634
3635uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003636 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003637 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003638 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003639 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003640 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641 }
3642 return old;
3643}
3644
Marissa Wall713b63f2018-10-17 15:42:43 -07003645bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003646 // to prevent onHandleDestroyed from being called while the lock is held,
3647 // we must keep a copy of the transactions (specifically the composer
3648 // states) around outside the scope of the lock
3649 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003650 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003651 {
3652 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003653
Valerie Haufce31b82019-04-30 16:41:14 -07003654 auto it = mTransactionQueues.begin();
3655 while (it != mTransactionQueues.end()) {
3656 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003657
Valerie Haufce31b82019-04-30 16:41:14 -07003658 while (!transactionQueue.empty()) {
3659 const auto& transaction = transactionQueue.front();
3660 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3661 transaction.states)) {
3662 setTransactionFlags(eTransactionFlushNeeded);
3663 break;
3664 }
3665 transactions.push_back(transaction);
3666 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3667 mPendingInputWindowCommands, transaction.desiredPresentTime,
3668 transaction.buffer, transaction.callback,
3669 transaction.postTime, transaction.privileged,
3670 /*isMainThread*/ true);
3671 transactionQueue.pop();
3672 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003673 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003674
Valerie Haufce31b82019-04-30 16:41:14 -07003675 if (transactionQueue.empty()) {
3676 it = mTransactionQueues.erase(it);
3677 mTransactionCV.broadcast();
3678 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003679 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003680 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003681 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003682 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003683 return flushedATransaction;
3684}
3685
3686bool SurfaceFlinger::transactionFlushNeeded() {
3687 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003688}
3689
chaviwca27f252018-02-06 16:46:39 -08003690bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3691 for (const ComposerState& state : states) {
3692 // Here we need to check that the interface we're given is indeed
3693 // one of our own. A malicious client could give us a nullptr
3694 // IInterface, or one of its own or even one of our own but a
3695 // different type. All these situations would cause us to crash.
3696 if (state.client == nullptr) {
3697 return true;
3698 }
3699
3700 sp<IBinder> binder = IInterface::asBinder(state.client);
3701 if (binder == nullptr) {
3702 return true;
3703 }
3704
3705 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3706 return true;
3707 }
3708 }
3709 return false;
3710}
3711
Marissa Wall17b4e452018-12-26 16:32:34 -08003712bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3713 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003714 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003715 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3716 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3717 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3718 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3719 return false;
3720 }
3721
Marissa Wall713b63f2018-10-17 15:42:43 -07003722 for (const ComposerState& state : states) {
3723 const layer_state_t& s = state.state;
3724 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3725 continue;
3726 }
3727 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003728 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003729 }
3730 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003731 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003732}
3733
3734void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3735 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003736 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003737 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003738 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003739 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003740 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003741 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003742
Valerie Haubc6ddb12019-03-08 11:10:15 -08003743 const int64_t postTime = systemTime();
3744
Robert Carr14167e02019-02-13 13:50:55 -08003745 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3746
Mathias Agopian698c0872011-06-28 19:09:31 -07003747 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003748
chaviwca27f252018-02-06 16:46:39 -08003749 if (containsAnyInvalidClientState(states)) {
3750 return;
3751 }
3752
Marissa Wall713b63f2018-10-17 15:42:43 -07003753 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003754 auto itr = mTransactionQueues.find(applyToken);
3755 // if this is an animation frame, wait until prior animation frame has
3756 // been applied by SF
3757 if (flags & eAnimation) {
3758 while (itr != mTransactionQueues.end()) {
3759 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3760 if (CC_UNLIKELY(err != NO_ERROR)) {
3761 ALOGW_IF(err == TIMED_OUT,
3762 "setTransactionState timed out "
3763 "waiting for animation frame to apply");
3764 break;
3765 }
3766 itr = mTransactionQueues.find(applyToken);
3767 }
3768 }
3769 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003770 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003771 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003772 uncacheBuffer, listenerCallbacks, postTime,
3773 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003774 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003775 return;
3776 }
3777
Valerie Haubc6ddb12019-03-08 11:10:15 -08003778 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003779 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003780}
3781
3782void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003783 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003784 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003785 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003786 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003787 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003788 const int64_t postTime, bool privileged,
3789 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003790 uint32_t transactionFlags = 0;
3791
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003792 if (flags & eAnimation) {
3793 // For window updates that are part of an animation we must wait for
3794 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003795 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003796 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003797 if (CC_UNLIKELY(err != NO_ERROR)) {
3798 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003799 // caller after a few seconds.
3800 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3801 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003802 mAnimTransactionPending = false;
3803 break;
3804 }
3805 }
3806 }
3807
chaviwca27f252018-02-06 16:46:39 -08003808 for (const DisplayState& display : displays) {
3809 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003810 }
3811
Marissa Walld600d572019-03-26 15:38:50 -07003812 // In case the client has sent a Transaction that should receive callbacks but without any
3813 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3814 // to the callback thread so it can send an empty callback
3815 if (!listenerCallbacks.empty()) {
3816 mTransactionCompletedThread.run();
3817 }
3818 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3819 mTransactionCompletedThread.addCallback(listener, callbackIds);
3820 }
3821
Marissa Walle2ffb422018-10-12 11:33:52 -07003822 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003823 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003824 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3825 postTime, privileged);
3826 }
3827
Marissa Walle2ffb422018-10-12 11:33:52 -07003828 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003829 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003830 mTransactionCompletedThread.sendCallbacks();
3831 }
3832 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003833
chaviw273171b2018-12-26 11:46:30 -08003834 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3835
Marissa Wall947d34e2019-03-29 14:03:53 -07003836 if (uncacheBuffer.isValid()) {
3837 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003838 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003839 }
3840
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003841 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3842 // anyway. This can be used as a flush mechanism for previous async transactions.
3843 // Empty animation transaction can be used to simulate back-pressure, so also force a
3844 // transaction for empty animation transactions.
3845 if (transactionFlags == 0 &&
3846 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003847 transactionFlags = eTransactionNeeded;
3848 }
3849
Marissa Wall06255332019-03-27 13:48:27 -07003850 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3851 // so we don't have to wake up again next frame to preform an uneeded traversal.
3852 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3853 transactionFlags = transactionFlags & (~eTraversalNeeded);
3854 mTraversalNeededMainThread = true;
3855 }
3856
Mathias Agopian386aa982011-11-07 21:58:03 -08003857 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003858 if (mInterceptor->isEnabled()) {
3859 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003860 }
Irvel468051e2016-06-13 16:44:44 -07003861
Mathias Agopian386aa982011-11-07 21:58:03 -08003862 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003863 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3864 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003865 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003866
3867 // if this is a synchronous transaction, wait for it to take effect
3868 // before returning.
3869 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003870 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003871 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003872 if (flags & eAnimation) {
3873 mAnimTransactionPending = true;
3874 }
chaviw4fe36852019-04-15 16:25:49 -07003875 if (mPendingInputWindowCommands.syncInputWindows) {
3876 mPendingSyncInputWindows = true;
3877 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003878
3879 // applyTransactionState can be called by either the main SF thread or by
3880 // another process through setTransactionState. While a given process may wish
3881 // to wait on synchronous transactions, the main SF thread should never
3882 // be blocked. Therefore, we only wait if isMainThread is false.
3883 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003884 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3885 if (CC_UNLIKELY(err != NO_ERROR)) {
3886 // just in case something goes wrong in SF, return to the
3887 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003888 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3889 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003890 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003891 break;
3892 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894 }
3895}
3896
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003897uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3898 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3899 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003900
Mathias Agopiane57f2922012-08-09 16:29:12 -07003901 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003902 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3903
3904 const uint32_t what = s.what;
3905 if (what & DisplayState::eSurfaceChanged) {
3906 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3907 state.surface = s.surface;
3908 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003909 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003910 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003911 if (what & DisplayState::eLayerStackChanged) {
3912 if (state.layerStack != s.layerStack) {
3913 state.layerStack = s.layerStack;
3914 flags |= eDisplayTransactionNeeded;
3915 }
3916 }
3917 if (what & DisplayState::eDisplayProjectionChanged) {
3918 if (state.orientation != s.orientation) {
3919 state.orientation = s.orientation;
3920 flags |= eDisplayTransactionNeeded;
3921 }
3922 if (state.frame != s.frame) {
3923 state.frame = s.frame;
3924 flags |= eDisplayTransactionNeeded;
3925 }
3926 if (state.viewport != s.viewport) {
3927 state.viewport = s.viewport;
3928 flags |= eDisplayTransactionNeeded;
3929 }
3930 }
3931 if (what & DisplayState::eDisplaySizeChanged) {
3932 if (state.width != s.width) {
3933 state.width = s.width;
3934 flags |= eDisplayTransactionNeeded;
3935 }
3936 if (state.height != s.height) {
3937 state.height = s.height;
3938 flags |= eDisplayTransactionNeeded;
3939 }
3940 }
3941
Mathias Agopiane57f2922012-08-09 16:29:12 -07003942 return flags;
3943}
3944
Robert Carr14167e02019-02-13 13:50:55 -08003945bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003946 IPCThreadState* ipc = IPCThreadState::self();
3947 const int pid = ipc->getCallingPid();
3948 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003949 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003950 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003951 return false;
3952 }
3953 return true;
3954}
3955
Marissa Wall3dad52d2019-03-22 14:03:19 -07003956uint32_t SurfaceFlinger::setClientStateLocked(
3957 const ComposerState& composerState, int64_t desiredPresentTime,
3958 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3959 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003960 const layer_state_t& s = composerState.state;
3961 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3962
Mathias Agopian13127d82013-03-05 17:47:11 -08003963 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003964 if (layer == nullptr) {
3965 return 0;
3966 }
3967
chaviw8b3871a2017-11-01 17:41:01 -07003968 uint32_t flags = 0;
3969
Garfield Tan8a3083e2018-12-03 13:21:07 -08003970 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003971 bool geometryAppliesWithResize =
3972 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003973
3974 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3975 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003976 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003977 layer->pushPendingState();
3978 }
3979
chaviw8b3871a2017-11-01 17:41:01 -07003980 if (what & layer_state_t::ePositionChanged) {
3981 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3982 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003983 }
chaviw8b3871a2017-11-01 17:41:01 -07003984 }
3985 if (what & layer_state_t::eLayerChanged) {
3986 // NOTE: index needs to be calculated before we update the state
3987 const auto& p = layer->getParent();
3988 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003989 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003990 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003991 mCurrentState.layersSortedByZ.removeAt(idx);
3992 mCurrentState.layersSortedByZ.add(layer);
3993 // we need traversal (state changed)
3994 // AND transaction (list changed)
3995 flags |= eTransactionNeeded|eTraversalNeeded;
3996 }
chaviw8b3871a2017-11-01 17:41:01 -07003997 } else {
3998 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003999 flags |= eTransactionNeeded|eTraversalNeeded;
4000 }
4001 }
chaviw8b3871a2017-11-01 17:41:01 -07004002 }
4003 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004004 // NOTE: index needs to be calculated before we update the state
4005 const auto& p = layer->getParent();
4006 if (p == nullptr) {
4007 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4008 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4009 mCurrentState.layersSortedByZ.removeAt(idx);
4010 mCurrentState.layersSortedByZ.add(layer);
4011 // we need traversal (state changed)
4012 // AND transaction (list changed)
4013 flags |= eTransactionNeeded|eTraversalNeeded;
4014 }
4015 } else {
4016 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4017 flags |= eTransactionNeeded|eTraversalNeeded;
4018 }
chaviw8b3871a2017-11-01 17:41:01 -07004019 }
4020 }
4021 if (what & layer_state_t::eSizeChanged) {
4022 if (layer->setSize(s.w, s.h)) {
4023 flags |= eTraversalNeeded;
4024 }
4025 }
4026 if (what & layer_state_t::eAlphaChanged) {
4027 if (layer->setAlpha(s.alpha))
4028 flags |= eTraversalNeeded;
4029 }
4030 if (what & layer_state_t::eColorChanged) {
4031 if (layer->setColor(s.color))
4032 flags |= eTraversalNeeded;
4033 }
Peiyong Lind3788632018-09-18 16:01:31 -07004034 if (what & layer_state_t::eColorTransformChanged) {
4035 if (layer->setColorTransform(s.colorTransform)) {
4036 flags |= eTraversalNeeded;
4037 }
4038 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004039 if (what & layer_state_t::eBackgroundColorChanged) {
4040 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4041 flags |= eTraversalNeeded;
4042 }
4043 }
chaviw8b3871a2017-11-01 17:41:01 -07004044 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004045 // TODO: b/109894387
4046 //
4047 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4048 // rotation. To see the problem observe that if we have a square parent, and a child
4049 // of the same size, then we rotate the child 45 degrees around it's center, the child
4050 // must now be cropped to a non rectangular 8 sided region.
4051 //
4052 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4053 // private API, and the WindowManager only uses rotation in one case, which is on a top
4054 // level layer in which cropping is not an issue.
4055 //
4056 // However given that abuse of rotation matrices could lead to surfaces extending outside
4057 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4058 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4059 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004060 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004061 flags |= eTraversalNeeded;
4062 }
4063 if (what & layer_state_t::eTransparentRegionChanged) {
4064 if (layer->setTransparentRegionHint(s.transparentRegion))
4065 flags |= eTraversalNeeded;
4066 }
4067 if (what & layer_state_t::eFlagsChanged) {
4068 if (layer->setFlags(s.flags, s.mask))
4069 flags |= eTraversalNeeded;
4070 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004071 if (what & layer_state_t::eCropChanged_legacy) {
4072 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004073 flags |= eTraversalNeeded;
4074 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004075 if (what & layer_state_t::eCornerRadiusChanged) {
4076 if (layer->setCornerRadius(s.cornerRadius))
4077 flags |= eTraversalNeeded;
4078 }
chaviw8b3871a2017-11-01 17:41:01 -07004079 if (what & layer_state_t::eLayerStackChanged) {
4080 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4081 // We only allow setting layer stacks for top level layers,
4082 // everything else inherits layer stack from its parent.
4083 if (layer->hasParent()) {
4084 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4085 layer->getName().string());
4086 } else if (idx < 0) {
4087 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4088 "that also does not appear in the top level layer list. Something"
4089 " has gone wrong.", layer->getName().string());
4090 } else if (layer->setLayerStack(s.layerStack)) {
4091 mCurrentState.layersSortedByZ.removeAt(idx);
4092 mCurrentState.layersSortedByZ.add(layer);
4093 // we need traversal (state changed)
4094 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004095 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004096 }
4097 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004098 if (what & layer_state_t::eDeferTransaction_legacy) {
4099 if (s.barrierHandle_legacy != nullptr) {
4100 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4101 } else if (s.barrierGbp_legacy != nullptr) {
4102 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004103 if (authenticateSurfaceTextureLocked(gbp)) {
4104 const auto& otherLayer =
4105 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004106 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004107 } else {
4108 ALOGE("Attempt to defer transaction to to an"
4109 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004110 }
4111 }
chaviw8b3871a2017-11-01 17:41:01 -07004112 // We don't trigger a traversal here because if no other state is
4113 // changed, we don't want this to cause any more work
4114 }
4115 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004116 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004117 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004118 if (!hadParent) {
4119 mCurrentState.layersSortedByZ.remove(layer);
4120 }
chaviw8b3871a2017-11-01 17:41:01 -07004121 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004122 }
chaviw8b3871a2017-11-01 17:41:01 -07004123 }
4124 if (what & layer_state_t::eReparentChildren) {
4125 if (layer->reparentChildren(s.reparentHandle)) {
4126 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004127 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004128 }
chaviw8b3871a2017-11-01 17:41:01 -07004129 if (what & layer_state_t::eDetachChildren) {
4130 layer->detachChildren();
4131 }
4132 if (what & layer_state_t::eOverrideScalingModeChanged) {
4133 layer->setOverrideScalingMode(s.overrideScalingMode);
4134 // We don't trigger a traversal here because if no other state is
4135 // changed, we don't want this to cause any more work
4136 }
Marissa Wall61c58622018-07-18 10:12:20 -07004137 if (what & layer_state_t::eTransformChanged) {
4138 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4139 }
4140 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4141 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4142 flags |= eTraversalNeeded;
4143 }
4144 if (what & layer_state_t::eCropChanged) {
4145 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4146 }
Marissa Wall861616d2018-10-22 12:52:23 -07004147 if (what & layer_state_t::eFrameChanged) {
4148 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4149 }
Marissa Wall61c58622018-07-18 10:12:20 -07004150 if (what & layer_state_t::eAcquireFenceChanged) {
4151 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4152 }
4153 if (what & layer_state_t::eDataspaceChanged) {
4154 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4155 }
4156 if (what & layer_state_t::eHdrMetadataChanged) {
4157 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4158 }
4159 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4160 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4161 }
4162 if (what & layer_state_t::eApiChanged) {
4163 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4164 }
4165 if (what & layer_state_t::eSidebandStreamChanged) {
4166 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4167 }
Robert Carr720e5062018-07-30 17:45:14 -07004168 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004169 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004170 layer->setInputInfo(s.inputInfo);
4171 flags |= eTraversalNeeded;
4172 } else {
4173 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4174 }
Robert Carr720e5062018-07-30 17:45:14 -07004175 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004176 if (what & layer_state_t::eMetadataChanged) {
4177 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4178 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004179 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4180 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4181 flags |= eTraversalNeeded;
4182 }
4183 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004184 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004185 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004186 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004187 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4188 }
4189 }
Marissa Wall78b72202019-03-15 14:58:34 -07004190 bool bufferChanged = what & layer_state_t::eBufferChanged;
4191 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4192 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004193 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07004194 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004195 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
4196 if (success) {
4197 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
4198 success = ClientCache::getInstance()
4199 .registerErasedRecipient(s.cachedBuffer,
4200 wp<ClientCache::ErasedRecipient>(this));
4201 if (!success) {
4202 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
4203 }
4204 }
Marissa Wall78b72202019-03-15 14:58:34 -07004205 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004206 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004207 } else if (bufferChanged) {
4208 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004209 }
Marissa Wall78b72202019-03-15 14:58:34 -07004210 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004211 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004212 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004213 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004214 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004215 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4216 // Do not put anything that updates layer state or modifies flags after
4217 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004218 return flags;
4219}
4220
chaviw273171b2018-12-26 11:46:30 -08004221uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4222 uint32_t flags = 0;
4223 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4224 flags |= eTraversalNeeded;
4225 }
4226
chaviwa911b102019-02-14 10:18:33 -08004227 if (inputWindowCommands.syncInputWindows) {
4228 flags |= eTraversalNeeded;
4229 }
4230
Vishnu Nairec0ab382019-02-13 15:32:56 -08004231 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004232 return flags;
4233}
4234
Marissa Wall2d814fb2019-04-09 18:52:57 +00004235status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4236 uint32_t h, PixelFormat format, uint32_t flags,
4237 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004238 sp<IGraphicBufferProducer>* gbp,
4239 const sp<IBinder>& parentHandle,
4240 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004241 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004242 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004243 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004244 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004245 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004246
Robert Carrc0df3122019-04-11 13:18:21 -07004247 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4248 "Expected only one of parentLayer or parentHandle to be non-null. "
4249 "Programmer error?");
4250
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004251 status_t result = NO_ERROR;
4252
4253 sp<Layer> layer;
4254
Cody Northropbc755282017-03-31 12:00:08 -06004255 String8 uniqueName = getUniqueLayerName(name);
4256
Evan Roskya1f1e152019-01-24 16:17:46 -08004257 bool primaryDisplayOnly = false;
4258
4259 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4260 // TODO b/64227542
4261 if (metadata.has(METADATA_WINDOW_TYPE)) {
4262 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4263 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004264 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004265 primaryDisplayOnly = true;
4266 }
4267 }
4268
Mathias Agopian3165cc22012-08-08 19:42:09 -07004269 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004270 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004271 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4272 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004273
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004274 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004275 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004276 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4277 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004278 break;
chaviw13fdc492017-06-27 12:40:18 -07004279 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004280 // check if buffer size is set for color layer.
4281 if (w > 0 || h > 0) {
4282 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4283 int(w), int(h));
4284 return BAD_VALUE;
4285 }
4286
Evan Roskya1f1e152019-01-24 16:17:46 -08004287 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4288 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004289 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004290 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004291 // check if buffer size is set for container layer.
4292 if (w > 0 || h > 0) {
4293 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4294 int(w), int(h));
4295 return BAD_VALUE;
4296 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004297 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4298 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004299 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004300 default:
4301 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004302 break;
4303 }
4304
Dan Stoza7d89d062015-04-30 13:29:25 -07004305 if (result != NO_ERROR) {
4306 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004307 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004308
Evan Roskya1f1e152019-01-24 16:17:46 -08004309 if (primaryDisplayOnly) {
4310 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004311 }
4312
Robert Carrb89ea9d2018-12-10 13:01:14 -08004313 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004314 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4315 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004316 if (result != NO_ERROR) {
4317 return result;
4318 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004319 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004320
4321 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004322 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004323}
4324
Cody Northropbc755282017-03-31 12:00:08 -06004325String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4326{
4327 bool matchFound = true;
4328 uint32_t dupeCounter = 0;
4329
4330 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4331 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4332
Dan Stoza436ccf32018-06-21 12:10:12 -07004333 // Grab the state lock since we're accessing mCurrentState
4334 Mutex::Autolock lock(mStateLock);
4335
Cody Northropbc755282017-03-31 12:00:08 -06004336 // Loop over layers until we're sure there is no matching name
4337 while (matchFound) {
4338 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004339 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004340 if (layer->getName() == uniqueName) {
4341 matchFound = true;
4342 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4343 }
4344 });
4345 }
4346
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004347 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4348 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004349
4350 return uniqueName;
4351}
4352
Marissa Wallfd668622018-05-10 10:21:13 -07004353status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4354 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004355 LayerMetadata metadata, PixelFormat& format,
4356 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004357 sp<IGraphicBufferProducer>* gbp,
4358 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004359 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004360 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004361 case PIXEL_FORMAT_TRANSPARENT:
4362 case PIXEL_FORMAT_TRANSLUCENT:
4363 format = PIXEL_FORMAT_RGBA_8888;
4364 break;
4365 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004366 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004367 break;
4368 }
4369
Evan Roskya1f1e152019-01-24 16:17:46 -08004370 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4371 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004372 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004373 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004374 *handle = layer->getHandle();
4375 *gbp = layer->getProducer();
4376 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004377 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004378
Marissa Wallfd668622018-05-10 10:21:13 -07004379 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004380 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004381}
4382
Marissa Wall61c58622018-07-18 10:12:20 -07004383status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4384 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004385 LayerMetadata metadata, sp<IBinder>* handle,
4386 sp<Layer>* outLayer) {
4387 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4388 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004389 *handle = layer->getHandle();
4390 *outLayer = layer;
4391
4392 return NO_ERROR;
4393}
4394
Evan Roskya1f1e152019-01-24 16:17:46 -08004395status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4396 uint32_t h, uint32_t flags, LayerMetadata metadata,
4397 sp<IBinder>* handle, sp<Layer>* outLayer) {
4398 *outLayer = getFactory().createColorLayer(
4399 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004400 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004401 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004402}
4403
Evan Roskya1f1e152019-01-24 16:17:46 -08004404status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4405 uint32_t w, uint32_t h, uint32_t flags,
4406 LayerMetadata metadata, sp<IBinder>* handle,
4407 sp<Layer>* outLayer) {
4408 *outLayer = getFactory().createContainerLayer(
4409 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004410 *handle = (*outLayer)->getHandle();
4411 return NO_ERROR;
4412}
4413
4414
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004415void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004416 mLayersPendingRemoval.add(layer);
4417 mLayersRemoved = true;
4418 setTransactionFlags(eTransactionNeeded);
4419}
4420
Robert Carr695d5282018-12-18 15:27:58 -08004421void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004422{
Robert Carr2e102c92018-10-23 12:11:15 -07004423 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004424 // If a layer has a parent, we allow it to out-live it's handle
4425 // with the idea that the parent holds a reference and will eventually
4426 // be cleaned up. However no one cleans up the top-level so we do so
4427 // here.
4428 if (layer->getParent() == nullptr) {
4429 mCurrentState.layersSortedByZ.remove(layer);
4430 }
4431 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004432
4433 auto it = mLayersByLocalBinderToken.begin();
4434 while (it != mLayersByLocalBinderToken.end()) {
4435 if (it->second == layer) {
4436 it = mLayersByLocalBinderToken.erase(it);
4437 } else {
4438 it++;
4439 }
4440 }
4441
Robert Carr695d5282018-12-18 15:27:58 -08004442 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004443}
4444
Mathias Agopianb60314a2012-04-10 22:09:54 -07004445// ---------------------------------------------------------------------------
4446
Andy McFadden13a082e2012-08-24 10:16:42 -07004447void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004448 const auto display = getDefaultDisplayDeviceLocked();
4449 if (!display) return;
4450
4451 const sp<IBinder> token = display->getDisplayToken().promote();
4452 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004453
Jesse Hall01e29052013-02-19 16:13:35 -08004454 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004455 Vector<ComposerState> state;
4456 Vector<DisplayState> displays;
4457 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004458 d.what = DisplayState::eDisplayProjectionChanged |
4459 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004460 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004461 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004462 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004463 d.frame.makeInvalid();
4464 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004465 d.width = 0;
4466 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004467 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004468 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004469
Dominik Laskowskie9774092018-12-11 10:04:24 -08004470 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004471
Dominik Laskowski83b88212018-12-11 13:34:06 -08004472 const nsecs_t vsyncPeriod = getVsyncPeriod();
4473 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004474
Brian Andersond0010582017-03-07 13:20:31 -08004475 // Use phase of 0 since phase is not known.
4476 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004477 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004478 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004479}
4480
4481void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004482 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004483 postMessageAsync(
4484 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004485}
4486
Ady Abraham27c70212019-06-11 10:52:26 -07004487void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4488 if (mHWCVsyncState != enabled) {
4489 getHwComposer().setVsyncEnabled(displayId, enabled);
4490 mHWCVsyncState = enabled;
4491 }
4492}
4493
Dominik Laskowskie9774092018-12-11 10:04:24 -08004494void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004495 if (display->isVirtual()) {
4496 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004497 return;
4498 }
4499
Dominik Laskowski075d3172018-05-24 15:50:06 -07004500 const auto displayId = display->getId();
4501 LOG_ALWAYS_FATAL_IF(!displayId);
4502
Dominik Laskowski34157762018-10-31 13:07:19 -07004503 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004504
4505 int currentMode = display->getPowerMode();
4506 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004507 return;
4508 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004509
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004510 display->setPowerMode(mode);
4511
Lloyd Pique4dccc412018-01-22 17:21:36 -08004512 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004513 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004514 }
4515
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004516 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004517 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004518 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004519 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004520 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004521 mScheduler->onScreenAcquired(mAppConnectionHandle);
4522 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004523 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004524
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004525 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004526 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004527 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004528
4529 struct sched_param param = {0};
4530 param.sched_priority = 1;
4531 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4532 ALOGW("Couldn't set SCHED_FIFO on display on");
4533 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004534 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004535 // Turn off the display
4536 struct sched_param param = {0};
4537 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4538 ALOGW("Couldn't set SCHED_OTHER on display off");
4539 }
4540
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004541 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004542 mScheduler->disableHardwareVsync(true);
4543 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004544 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004545
Ady Abraham27c70212019-06-11 10:52:26 -07004546 // Make sure HWVsync is disabled before turning off the display
4547 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4548
Dominik Laskowski075d3172018-05-24 15:50:06 -07004549 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004550 mVisibleRegionsDirty = true;
4551 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004552 } else if (mode == HWC_POWER_MODE_DOZE ||
4553 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004554 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004555 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004556 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004557 mScheduler->onScreenAcquired(mAppConnectionHandle);
4558 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004559 }
4560 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4561 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004562 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004563 mScheduler->disableHardwareVsync(true);
4564 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004565 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004566 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004567 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004568 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004569 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004570 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004571
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004572 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004573 mTimeStats->setPowerMode(mode);
Steven Thomase9eb1832019-08-28 16:08:35 -07004574 mRefreshRateStats->setPowerMode(mode);
Ady Abraham24363172019-07-12 12:37:57 -07004575 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004576 }
4577
Dominik Laskowski34157762018-10-31 13:07:19 -07004578 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004579}
4580
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004581void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004582 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004583 const auto display = getDisplayDevice(displayToken);
4584 if (!display) {
4585 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4586 displayToken.get());
4587 } else if (display->isVirtual()) {
4588 ALOGW("Attempt to set power mode %d for virtual display", mode);
4589 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004590 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004591 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004592 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004593}
4594
4595// ---------------------------------------------------------------------------
4596
Dominik Laskowskic2867142019-01-21 11:33:38 -08004597status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4598 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004599 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004600
Mathias Agopianbd115332013-04-18 16:41:04 -07004601 IPCThreadState* ipc = IPCThreadState::self();
4602 const int pid = ipc->getCallingPid();
4603 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004604
Mathias Agopianbd115332013-04-18 16:41:04 -07004605 if ((uid != AID_SHELL) &&
4606 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4608 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004609 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004610 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004611 // (this would indicate SF is stuck, but we want to be able to
4612 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004613 status_t err = mStateLock.timedLock(s2ns(1));
4614 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004615 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004616 StringAppendF(&result,
4617 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4618 "(no locks held)\n",
4619 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004620 }
4621
Dominik Laskowskic2867142019-01-21 11:33:38 -08004622 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004623
Dominik Laskowskic2867142019-01-21 11:33:38 -08004624 static const std::unordered_map<std::string, Dumper> dumpers = {
4625 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4626 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4627 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004628 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004629 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004630 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004631 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4632 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004633 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4634 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4635 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4636 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4637 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4638 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004639 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004640 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4641 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004642
Dominik Laskowskic2867142019-01-21 11:33:38 -08004643 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004644
Dominik Laskowskic2867142019-01-21 11:33:38 -08004645 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4646 (it->second)(args, asProto, result);
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004647 } else if (!asProto) {
4648 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004649 }
4650
Mathias Agopian9795c422009-08-26 16:36:26 -07004651 if (locked) {
4652 mStateLock.unlock();
4653 }
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004654
4655 LayersProto layersProto = dumpProtoFromMainThread();
4656 if (asProto) {
4657 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4658 } else {
4659 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4660 result.append(LayerProtoParser::layerTreeToString(layerTree));
4661 result.append("\n");
4662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004663 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004664 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004665 return NO_ERROR;
4666}
4667
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004668status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4669 if (asProto && mTracing.isEnabled()) {
4670 mTracing.writeToFileAsync();
4671 }
4672
4673 return doDump(fd, DumpArgs(), asProto);
4674}
4675
Dominik Laskowskic2867142019-01-21 11:33:38 -08004676void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004677 mCurrentState.traverseInZOrder(
4678 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004679}
4680
Dominik Laskowskic2867142019-01-21 11:33:38 -08004681void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004682 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004683
Dominik Laskowskic2867142019-01-21 11:33:38 -08004684 if (args.size() > 1) {
4685 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004686 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004687 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004688 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004689 }
Robert Carr2047fae2016-11-28 14:09:09 -08004690 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004691 } else {
4692 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693 }
4694}
4695
Dominik Laskowskic2867142019-01-21 11:33:38 -08004696void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004697 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004698 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004699 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004700 }
Robert Carr2047fae2016-11-28 14:09:09 -08004701 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004702
Svetoslavd85084b2014-03-20 10:28:31 -07004703 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004704}
4705
Dominik Laskowskic2867142019-01-21 11:33:38 -08004706void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4707 mTimeStats->parseArgs(asProto, args, result);
4708}
4709
Jamie Gennis6547ff42013-07-16 20:12:42 -07004710// This should only be called from the main thread. Otherwise it would need
4711// the lock and should use mCurrentState rather than mDrawingState.
4712void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004713 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004714 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004715 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004716
4717 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4718}
4719
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004721 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004722
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004723 if (isLayerTripleBufferingDisabled())
4724 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004725
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4727 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4728 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4729 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4730 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4731 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004732 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004733}
4734
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004735void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004736 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004737 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004738 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004739 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004740
Ady Abraham97d04232019-03-05 19:48:12 -08004741 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004742 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4743 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004744 StringAppendF(&result, "Allowed Display Configs: ");
4745 for (int32_t configId : mAllowedDisplayConfigs) {
Steven Thomase9eb1832019-08-28 16:08:35 -07004746 StringAppendF(&result, "%" PRIu32 " Hz, ",
4747 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004748 }
4749 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4750 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004751 mScheduler->dump(mAppConnectionHandle, result);
Steven Thomase9eb1832019-08-28 16:08:35 -07004752 StringAppendF(&result, "+ Refresh rate switching: %s\n",
4753 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004754}
4755
Yiwei Zhang5434a782018-12-05 18:06:32 -08004756void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4757 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004758 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4759 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004760 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004761 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004762 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004763 }
David Sodman4a36e932017-11-07 14:29:47 -08004764 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004765 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004766 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4768 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004769}
4770
Dan Stozae77c7662016-05-13 11:37:28 -07004771void SurfaceFlinger::recordBufferingStats(const char* layerName,
4772 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004773 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4774 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004775 for (const auto& segment : history) {
4776 if (!segment.usedThirdBuffer) {
4777 stats.twoBufferTime += segment.totalTime;
4778 }
4779 if (segment.occupancyAverage < 1.0f) {
4780 stats.doubleBufferedTime += segment.totalTime;
4781 } else if (segment.occupancyAverage < 2.0f) {
4782 stats.tripleBufferedTime += segment.totalTime;
4783 }
4784 ++stats.numSegments;
4785 stats.totalTime += segment.totalTime;
4786 }
4787}
4788
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4790 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004791
4792 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4793 const size_t count = currentLayers.size();
4794 for (size_t i=0 ; i<count ; i++) {
4795 currentLayers[i]->dumpFrameEvents(result);
4796 }
4797}
4798
Yiwei Zhang5434a782018-12-05 18:06:32 -08004799void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004800 result.append("Buffering stats:\n");
4801 result.append(" [Layer name] <Active time> <Two buffer> "
4802 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004803 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004804 typedef std::tuple<std::string, float, float, float> BufferTuple;
4805 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004806 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004807 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004808 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004809 if (stats.numSegments == 0) {
4810 continue;
4811 }
4812 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4813 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4814 stats.totalTime;
4815 float doubleBufferRatio = static_cast<float>(
4816 stats.doubleBufferedTime) / stats.totalTime;
4817 float tripleBufferRatio = static_cast<float>(
4818 stats.tripleBufferedTime) / stats.totalTime;
4819 sorted.insert({activeTime, {name, twoBufferRatio,
4820 doubleBufferRatio, tripleBufferRatio}});
4821 }
4822 for (const auto& sortedPair : sorted) {
4823 float activeTime = sortedPair.first;
4824 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4826 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004827 }
4828 result.append("\n");
4829}
4830
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004832 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004833 const auto displayId = display->getId();
4834 if (!displayId) {
4835 continue;
4836 }
4837 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004838 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004839 continue;
4840 }
4841
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 StringAppendF(&result,
4843 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4844 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004845 uint8_t port;
4846 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004847 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004848 result.append("no identification data\n");
4849 continue;
4850 }
4851
4852 if (!isEdid(data)) {
4853 result.append("unknown identification data: ");
4854 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004856 }
4857 result.append("\n");
4858 continue;
4859 }
4860
4861 const auto edid = parseEdid(data);
4862 if (!edid) {
4863 result.append("invalid EDID: ");
4864 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004865 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004866 }
4867 result.append("\n");
4868 continue;
4869 }
4870
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004872 result.append(edid->displayName.data(), edid->displayName.length());
4873 result.append("\"\n");
4874 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004875}
4876
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004878 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004879 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4880 StringAppendF(&result, "DisplayColorSetting: %s\n",
4881 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004882
4883 // TODO: print out if wide-color mode is active or not
4884
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004885 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 const auto displayId = display->getId();
4887 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004888 continue;
4889 }
4890
Yiwei Zhang5434a782018-12-05 18:06:32 -08004891 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004892 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004893 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004895 }
4896
Lloyd Pique32cbe282018-10-19 13:09:22 -07004897 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004898 StringAppendF(&result, " Current color mode: %s (%d)\n",
4899 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004900 }
4901 result.append("\n");
4902}
4903
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004904LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004905 LayersProto layersProto;
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004906 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004907 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004908 layer->writeToProtoDrawingState(layerProto, traceFlags);
4909 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004910 });
4911
4912 return layersProto;
4913}
4914
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004915LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4916 LayersProto layersProto;
4917 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4918 return layersProto;
4919}
4920
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004921LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4922 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004923 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004924
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004925 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004926 resolution->set_w(displayDevice->getWidth());
4927 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004928
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004929 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004930 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004931
Lloyd Pique32cbe282018-10-19 13:09:22 -07004932 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4933 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4934 layersProto.set_global_transform(displayState.orientation);
4935
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004936 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004937 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004938 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004939 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004940 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004941 layer->writeToProtoCompositionState(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004942 }
4943 });
4944
4945 return layersProto;
4946}
4947
Dominik Laskowskic2867142019-01-21 11:33:38 -08004948void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4949 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004950 Colorizer colorizer(colorize);
4951
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004952 // figure out if we're stuck somewhere
4953 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004954 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004955 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4956
4957 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004958 * Dump library configuration.
4959 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004960
4961 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004962 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004963 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004964 appendSfConfigString(result);
4965 appendUiConfigString(result);
4966 appendGuiConfigString(result);
4967 result.append("\n");
4968
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004969 result.append("\nDisplay identification data:\n");
4970 dumpDisplayIdentificationData(result);
4971
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004972 result.append("\nWide-Color information:\n");
4973 dumpWideColorInfo(result);
4974
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004975 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004976 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004977 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004978 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004979 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004980
Andy McFadden41d67d72014-04-25 16:58:34 -07004981 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004982 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004983 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004984 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004985 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004986
Dan Stozab90cf072015-03-05 11:05:59 -08004987 dumpStaticScreenStats(result);
4988 result.append("\n");
4989
Alec Mouri40189b02019-03-05 15:07:54 -08004990 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4991 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4992 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004993
Dan Stozae77c7662016-05-13 11:37:28 -07004994 dumpBufferingStats(result);
4995
Andy McFadden4803b742012-09-24 19:07:20 -07004996 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004997 * Dump the visible layer list
4998 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004999 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005000 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
5001 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
5002 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005003 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005004
Chia-I Wu2f884132018-09-13 15:17:58 -07005005 {
Lloyd Pique207def92019-02-28 16:09:52 -08005006 StringAppendF(&result, "Composition layers\n");
5007 mDrawingState.traverseInZOrder([&](Layer* layer) {
5008 auto compositionLayer = layer->getCompositionLayer();
5009 if (compositionLayer) compositionLayer->dump(result);
5010 });
5011 }
5012
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005013 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005014 * Dump Display state
5015 */
5016
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005017 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005018 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005019 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005020 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005021 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005022 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005023 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005024
5025 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005026 * Dump SurfaceFlinger global state
5027 */
5028
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005029 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005030 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005031 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005032
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005033 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005034
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005035 DebugEGLImageTracker::getInstance()->dump(result);
5036
Dominik Laskowski075d3172018-05-24 15:50:06 -07005037 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005038 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5039 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005040 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5041 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005042 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005043 StringAppendF(&result,
5044 " transaction-flags : %08x\n"
5045 " gpu_to_cpu_unsupported : %d\n",
5046 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005047
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005048 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005049 displayId && getHwComposer().isConnected(*displayId)) {
5050 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005051 StringAppendF(&result,
5052 " refresh-rate : %f fps\n"
5053 " x-dpi : %f\n"
5054 " y-dpi : %f\n",
5055 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5056 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005057 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005058
Yiwei Zhang5434a782018-12-05 18:06:32 -08005059 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005060
Dan Stozae22aec72016-08-01 13:20:59 -07005061 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005062 * Tracing state
5063 */
5064 mTracing.dump(result);
5065 result.append("\n");
5066
5067 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005068 * HWC layer minidump
5069 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005070 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005071 const auto displayId = display->getId();
5072 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005073 continue;
5074 }
5075
Yiwei Zhang5434a782018-12-05 18:06:32 -08005076 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005077 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005078 const sp<DisplayDevice> displayDevice = display;
5079 mCurrentState.traverseInZOrder(
5080 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005081 result.append("\n");
5082 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005083
5084 /*
5085 * Dump HWComposer state
5086 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005087 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005088 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005089 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005090 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005091 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005092 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005093
5094 /*
5095 * Dump gralloc state
5096 */
5097 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5098 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005099
5100 /*
5101 * Dump VrFlinger state if in use.
5102 */
5103 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5104 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005105 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005106 result.append("\n");
5107 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005108
5109 /**
5110 * Scheduler dump state.
5111 */
Ana Krulecc2870422019-01-29 19:00:58 -08005112 result.append("\nScheduler state:\n");
5113 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005114 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Steven Thomase9eb1832019-08-28 16:08:35 -07005115 result.append(mRefreshRateStats->doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005116
5117 result.append(mTimeStats->miniDump());
5118 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005119}
5120
Dominik Laskowski075d3172018-05-24 15:50:06 -07005121const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005122 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005123 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005124 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005125 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005126 }
5127 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005128
Dominik Laskowski34157762018-10-31 13:07:19 -07005129 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005130 static const Vector<sp<Layer>> empty;
5131 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005132}
5133
Chia-I Wu28f320b2018-05-03 11:02:56 -07005134void SurfaceFlinger::updateColorMatrixLocked() {
5135 mat4 colorMatrix;
5136 if (mGlobalSaturationFactor != 1.0f) {
5137 // Rec.709 luma coefficients
5138 float3 luminance{0.213f, 0.715f, 0.072f};
5139 luminance *= 1.0f - mGlobalSaturationFactor;
5140 mat4 saturationMatrix = mat4(
5141 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5142 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5143 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5144 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5145 );
5146 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5147 } else {
5148 colorMatrix = mClientColorMatrix * mDaltonizer();
5149 }
5150
5151 if (mCurrentState.colorMatrix != colorMatrix) {
5152 mCurrentState.colorMatrix = colorMatrix;
5153 mCurrentState.colorMatrixChanged = true;
5154 setTransactionFlags(eTransactionNeeded);
5155 }
5156}
5157
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005158status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005159#pragma clang diagnostic push
5160#pragma clang diagnostic error "-Wswitch-enum"
5161 switch (static_cast<ISurfaceComposerTag>(code)) {
5162 // These methods should at minimum make sure that the client requested
5163 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005164 case BOOT_FINISHED:
5165 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005166 case CREATE_DISPLAY:
5167 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005168 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005169 case GET_ANIMATION_FRAME_STATS:
5170 case GET_HDR_CAPABILITIES:
5171 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005172 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005173 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005174 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005175 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005176 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005177 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005178 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005179 case GET_DISPLAYED_CONTENT_SAMPLE:
5180 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005181 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5182 IPCThreadState* ipc = IPCThreadState::self();
5183 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5184 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005185 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005186 }
Robert Carr1db73f62016-12-21 12:58:51 -08005187 return OK;
5188 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005189 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005190 IPCThreadState* ipc = IPCThreadState::self();
5191 const int pid = ipc->getCallingPid();
5192 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005193 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5194 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005195 return PERMISSION_DENIED;
5196 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005197 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005198 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005199 // Used by apps to hook Choreographer to SurfaceFlinger.
5200 case CREATE_DISPLAY_EVENT_CONNECTION:
5201 // The following calls are currently used by clients that do not
5202 // request necessary permissions. However, they do not expose any secret
5203 // information, so it is OK to pass them.
5204 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005205 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005206 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005207 case GET_PHYSICAL_DISPLAY_IDS:
5208 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005209 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005210 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005211 case GET_DISPLAY_CONFIGS:
5212 case GET_DISPLAY_STATS:
5213 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5214 // Calling setTransactionState is safe, because you need to have been
5215 // granted a reference to Client* and Handle* to do anything with it.
5216 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005217 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005218 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005219 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005220 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005221 case IS_WIDE_COLOR_DISPLAY:
5222 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5223 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005224 return OK;
5225 }
5226 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005227 case CAPTURE_SCREEN:
5228 case ADD_REGION_SAMPLING_LISTENER:
5229 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005230 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005231 IPCThreadState* ipc = IPCThreadState::self();
5232 const int pid = ipc->getCallingPid();
5233 const int uid = ipc->getCallingUid();
5234 if ((uid != AID_GRAPHICS) &&
5235 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5236 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5237 return PERMISSION_DENIED;
5238 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005239 return OK;
5240 }
5241 // The following codes are deprecated and should never be allowed to access SF.
5242 case CONNECT_DISPLAY_UNUSED:
5243 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5244 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5245 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005246 }
chaviw93df2ea2019-04-30 16:45:12 -07005247 case CAPTURE_SCREEN_BY_ID: {
5248 IPCThreadState* ipc = IPCThreadState::self();
5249 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005250 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005251 return OK;
5252 }
5253 return PERMISSION_DENIED;
5254 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005255 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005256
5257 // These codes are used for the IBinder protocol to either interrogate the recipient
5258 // side of the transaction for its canonical interface descriptor or to dump its state.
5259 // We let them pass by default.
5260 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5261 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5262 code == IBinder::SYSPROPS_TRANSACTION) {
5263 return OK;
5264 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005265 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005266 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005267 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005268 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5269 return OK;
5270 }
5271 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5272 return PERMISSION_DENIED;
5273#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005274}
5275
Ana Krulec13be8ad2018-08-21 02:43:56 +00005276status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5277 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005278 status_t credentialCheck = CheckTransactCodeCredentials(code);
5279 if (credentialCheck != OK) {
5280 return credentialCheck;
5281 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005282
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005283 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5284 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005285 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005286 IPCThreadState* ipc = IPCThreadState::self();
5287 const int uid = ipc->getCallingUid();
5288 if (CC_UNLIKELY(uid != AID_SYSTEM
5289 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005290 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005291 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005292 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005293 return PERMISSION_DENIED;
5294 }
5295 int n;
5296 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005297 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005298 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005299 return NO_ERROR;
5300 case 1002: // SHOW_UPDATES
5301 n = data.readInt32();
5302 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005303 invalidateHwcGeometry();
5304 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005305 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005306 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005307 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005308 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005309 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005310 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005311 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005312 setTransactionFlags(
5313 eTransactionNeeded|
5314 eDisplayTransactionNeeded|
5315 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005316 return NO_ERROR;
5317 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005318 case 1006:{ // send empty update
5319 signalRefresh();
5320 return NO_ERROR;
5321 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005322 case 1008: // toggle use of hw composer
5323 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005324 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005325 invalidateHwcGeometry();
5326 repaintEverything();
5327 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005328 case 1009: // toggle use of transform hint
5329 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005330 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005331 invalidateHwcGeometry();
5332 repaintEverything();
5333 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005334 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005335 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005336 reply->writeInt32(0);
5337 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005338 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005339 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005340 return NO_ERROR;
5341 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005342 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005343 if (!display) {
5344 return NAME_NOT_FOUND;
5345 }
5346
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005347 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005348 return NO_ERROR;
5349 }
5350 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005351 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005352 // daltonize
5353 n = data.readInt32();
5354 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005355 case 1:
5356 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5357 break;
5358 case 2:
5359 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5360 break;
5361 case 3:
5362 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5363 break;
5364 default:
5365 mDaltonizer.setType(ColorBlindnessType::None);
5366 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005367 }
5368 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005369 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005370 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005371 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005372 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005373
5374 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005375 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005376 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005377 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005378 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005379 // apply a color matrix
5380 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005381 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005382 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005383 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005384 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005385 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005386 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005387 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005388 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005389 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005390 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005391
5392 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5393 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005394 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005395 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5396 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5397 }
5398
Chia-I Wu28f320b2018-05-03 11:02:56 -07005399 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005400 return NO_ERROR;
5401 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005402 // This is an experimental interface
5403 // Needs to be shifted to proper binder interface when we productize
5404 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005405 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005406 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005407 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005408 return NO_ERROR;
5409 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005410 case 1017: {
5411 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005412 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005413 return NO_ERROR;
5414 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005415 case 1018: { // Modify Choreographer's phase offset
5416 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005417 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005418 return NO_ERROR;
5419 }
5420 case 1019: { // Modify SurfaceFlinger's phase offset
5421 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005422 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005423 return NO_ERROR;
5424 }
Irvel468051e2016-06-13 16:44:44 -07005425 case 1020: { // Layer updates interceptor
5426 n = data.readInt32();
5427 if (n) {
5428 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005429 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005430 }
5431 else{
5432 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005433 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005434 }
5435 return NO_ERROR;
5436 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005437 case 1021: { // Disable HWC virtual displays
5438 n = data.readInt32();
5439 mUseHwcVirtualDisplays = !n;
5440 return NO_ERROR;
5441 }
Romain Guy0147a172017-06-01 13:53:56 -07005442 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005443 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005444 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005445
Chia-I Wu28f320b2018-05-03 11:02:56 -07005446 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005447 return NO_ERROR;
5448 }
Romain Guy54f154a2017-10-24 21:40:32 +01005449 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005450 int32_t colorMode;
5451
Chia-I Wu0d711262018-05-21 15:19:35 -07005452 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005453 if (data.readInt32(&colorMode) == NO_ERROR) {
5454 mForceColorMode = static_cast<ColorMode>(colorMode);
5455 }
Romain Guy54f154a2017-10-24 21:40:32 +01005456 invalidateHwcGeometry();
5457 repaintEverything();
5458 return NO_ERROR;
5459 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005460 // Deprecate, use 1030 to check whether the device is color managed.
5461 case 1024: {
5462 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005463 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005464 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005465 n = data.readInt32();
5466 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005467 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005468 Mutex::Autolock lock(mStateLock);
5469 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005470 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005471 reply->writeInt32(NO_ERROR);
5472 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005473 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005474 bool writeFile = false;
5475 {
5476 Mutex::Autolock lock(mStateLock);
5477 mTracingEnabledChanged = true;
5478 writeFile = mTracing.disable();
5479 }
5480
5481 if (writeFile) {
5482 reply->writeInt32(mTracing.writeToFile());
5483 } else {
5484 reply->writeInt32(NO_ERROR);
5485 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005486 }
5487 return NO_ERROR;
5488 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005489 case 1026: { // Get layer tracing status
5490 reply->writeBool(mTracing.isEnabled());
5491 return NO_ERROR;
5492 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005493 // Is a DisplayColorSetting supported?
5494 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005495 const auto display = getDefaultDisplayDevice();
5496 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005497 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005498 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005499
5500 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5501 switch (setting) {
5502 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005503 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005504 break;
5505 case DisplayColorSetting::UNMANAGED:
5506 reply->writeBool(true);
5507 break;
5508 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005509 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005510 break;
5511 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005512 reply->writeBool(
5513 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005514 break;
5515 }
5516 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005517 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005518 // Is VrFlinger active?
5519 case 1028: {
5520 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005521 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005522 return NO_ERROR;
5523 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005524 // Set buffer size for SF tracing (value in KB)
5525 case 1029: {
5526 n = data.readInt32();
5527 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5528 ALOGW("Invalid buffer size: %d KB", n);
5529 reply->writeInt32(BAD_VALUE);
5530 return BAD_VALUE;
5531 }
5532
5533 ALOGD("Updating trace buffer to %d KB", n);
5534 mTracing.setBufferSize(n * 1024);
5535 reply->writeInt32(NO_ERROR);
5536 return NO_ERROR;
5537 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005538 // Is device color managed?
5539 case 1030: {
5540 reply->writeBool(useColorManagement);
5541 return NO_ERROR;
5542 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005543 // Override default composition data space
5544 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5545 // && adb shell stop zygote && adb shell start zygote
5546 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5547 // adb shell stop zygote && adb shell start zygote
5548 case 1031: {
5549 Mutex::Autolock _l(mStateLock);
5550 n = data.readInt32();
5551 if (n) {
5552 n = data.readInt32();
5553 if (n) {
5554 Dataspace dataspace = static_cast<Dataspace>(n);
5555 if (!validateCompositionDataspace(dataspace)) {
5556 return BAD_VALUE;
5557 }
5558 mDefaultCompositionDataspace = dataspace;
5559 }
5560 n = data.readInt32();
5561 if (n) {
5562 Dataspace dataspace = static_cast<Dataspace>(n);
5563 if (!validateCompositionDataspace(dataspace)) {
5564 return BAD_VALUE;
5565 }
5566 mWideColorGamutCompositionDataspace = dataspace;
5567 }
5568 } else {
5569 // restore composition data space.
5570 mDefaultCompositionDataspace = defaultCompositionDataspace;
5571 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5572 }
5573 return NO_ERROR;
5574 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005575 // Set trace flags
5576 case 1033: {
5577 n = data.readUint32();
5578 ALOGD("Updating trace flags to 0x%x", n);
5579 mTracing.setTraceFlags(n);
5580 reply->writeInt32(NO_ERROR);
5581 return NO_ERROR;
5582 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005583 case 1034: {
5584 // TODO(b/129297325): expose this via developer menu option
5585 n = data.readInt32();
Steven Thomase9eb1832019-08-28 16:08:35 -07005586 if (n && !mRefreshRateOverlay &&
5587 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005588 RefreshRateType type;
5589 {
5590 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5591 type = mDesiredActiveConfig.type;
5592 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005593 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005594 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005595 } else if (!n) {
5596 mRefreshRateOverlay.reset();
5597 }
5598 return NO_ERROR;
5599 }
Ady Abraham34392f72019-04-10 11:29:27 -07005600 case 1035: {
5601 n = data.readInt32();
5602 mDebugDisplayConfigSetByBackdoor = false;
5603 if (n >= 0) {
5604 const auto displayToken = getInternalDisplayToken();
5605 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5606 if (result != NO_ERROR) {
5607 return result;
5608 }
5609 mDebugDisplayConfigSetByBackdoor = true;
5610 }
5611 return NO_ERROR;
5612 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005613 }
5614 }
5615 return err;
5616}
5617
Steven Thomas6d8110b2017-08-31 18:24:21 -07005618void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005619 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005620 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005621}
5622
Ana Krulec7d1d6832018-12-27 11:10:09 -08005623void SurfaceFlinger::repaintEverythingForHWC() {
5624 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005625 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005626}
5627
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5629class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005630public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005631 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5632 ~WindowDisconnector() {
5633 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005634 }
5635
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005636private:
5637 ANativeWindow* mWindow;
5638 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005639};
5640
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005641status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005642 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5643 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005644 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005645 uint32_t reqWidth, uint32_t reqHeight,
5646 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005647 ISurfaceComposer::Rotation rotation,
5648 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005649 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005650
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005651 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005652
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005653 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5654
Chia-I Wu20261cb2018-08-23 12:55:44 -07005655 sp<DisplayDevice> display;
5656 {
5657 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005658
Chia-I Wu20261cb2018-08-23 12:55:44 -07005659 display = getDisplayDeviceLocked(displayToken);
5660 if (!display) return BAD_VALUE;
5661
Chia-I Wucb023152018-08-28 12:57:23 -07005662 // set the requested width/height to the logical display viewport size
5663 // by default
5664 if (reqWidth == 0 || reqHeight == 0) {
5665 reqWidth = uint32_t(display->getViewport().width());
5666 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005667 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005668 }
5669
Peiyong Lin0e003c92018-09-17 11:09:51 -07005670 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005671 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005672
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005673 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5674 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005675 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005676 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005677}
5678
chaviw93df2ea2019-04-30 16:45:12 -07005679static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5680 switch (colorMode) {
5681 case ColorMode::DISPLAY_P3:
5682 case ColorMode::BT2100_PQ:
5683 case ColorMode::BT2100_HLG:
5684 case ColorMode::DISPLAY_BT2020:
5685 return Dataspace::DISPLAY_P3;
5686 default:
5687 return Dataspace::V0_SRGB;
5688 }
5689}
5690
5691const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5692 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5693 if (displayToken) {
5694 return getDisplayDeviceLocked(displayToken);
5695 }
5696 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5697 // may not have a displayId.
5698 for (const auto& [token, display] : mDisplays) {
5699 if (display->getLayerStack() == displayOrLayerStack) {
5700 return display;
5701 }
5702 }
5703 return nullptr;
5704}
5705
5706status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5707 sp<GraphicBuffer>* outBuffer) {
5708 sp<DisplayDevice> display;
5709 uint32_t width;
5710 uint32_t height;
5711 ui::Transform::orientation_flags captureOrientation;
5712 {
5713 Mutex::Autolock _l(mStateLock);
5714 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5715 if (!display) {
5716 return BAD_VALUE;
5717 }
5718
5719 width = uint32_t(display->getViewport().width());
5720 height = uint32_t(display->getViewport().height());
5721
5722 captureOrientation = fromSurfaceComposerRotation(
5723 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005724 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5725 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5726 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5727 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5728 }
chaviw93df2ea2019-04-30 16:45:12 -07005729 *outDataspace =
5730 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5731 }
5732
5733 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5734 false /* captureSecureLayers */);
5735
5736 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5737 std::placeholders::_1);
5738 bool ignored = false;
5739 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5740 false /* useIdentityTransform */,
5741 ignored /* outCapturedSecureLayers */);
5742}
5743
Robert Carr866455f2019-04-02 16:28:26 -07005744status_t SurfaceFlinger::captureLayers(
5745 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5746 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5747 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5748 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005749 ATRACE_CALL();
5750
5751 class LayerRenderArea : public RenderArea {
5752 public:
Robert Carr578038f2018-03-09 12:25:24 -08005753 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005754 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5755 bool childrenOnly)
5756 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005757 mLayer(layer),
5758 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005759 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005760 mFlinger(flinger),
5761 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005762 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005763 Rect getBounds() const override {
5764 const Layer::State& layerState(mLayer->getDrawingState());
5765 return mLayer->getBufferSize(layerState);
5766 }
Marissa Wall61c58622018-07-18 10:12:20 -07005767 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005768 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005769 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005770 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005771 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005772 }
chaviwa76b2712017-09-20 12:02:26 -07005773 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005774 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005775 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005776 Rect getSourceCrop() const override {
5777 if (mCrop.isEmpty()) {
5778 return getBounds();
5779 } else {
5780 return mCrop;
5781 }
5782 }
Robert Carr578038f2018-03-09 12:25:24 -08005783 class ReparentForDrawing {
5784 public:
5785 const sp<Layer>& oldParent;
5786 const sp<Layer>& newParent;
5787
Vishnu Nair4351ad52019-02-11 14:13:02 -08005788 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5789 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005790 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005791 // Compute and cache the bounds for the new parent layer.
5792 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005793 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005794 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005795 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005796 };
5797
5798 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005799 const Rect sourceCrop = getSourceCrop();
5800 // no need to check rotation because there is none
5801 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5802 sourceCrop.height() != getReqHeight();
5803
Robert Carr578038f2018-03-09 12:25:24 -08005804 if (!mChildrenOnly) {
5805 mTransform = mLayer->getTransform().inverse();
5806 drawLayers();
5807 } else {
5808 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005809 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005810 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005811 bounds.getWidth(), bounds.getHeight(), 0,
5812 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005813
Vishnu Nair4351ad52019-02-11 14:13:02 -08005814 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005815 drawLayers();
5816 }
5817 }
chaviwa76b2712017-09-20 12:02:26 -07005818
chaviwa76b2712017-09-20 12:02:26 -07005819 private:
chaviw7206d492017-11-10 16:16:12 -08005820 const sp<Layer> mLayer;
5821 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005822
5823 // In the "childrenOnly" case we reparent the children to a screenshot
5824 // layer which has no properties set and which does not draw.
5825 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005826 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005827 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005828
5829 SurfaceFlinger* mFlinger;
5830 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005831 };
5832
Robert Carrc0df3122019-04-11 13:18:21 -07005833 int reqWidth = 0;
5834 int reqHeight = 0;
5835 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005836 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005837 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005838
Robert Carrc0df3122019-04-11 13:18:21 -07005839 {
5840 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005841
Robert Carrc0df3122019-04-11 13:18:21 -07005842 parent = fromHandle(layerHandleBinder);
5843 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5844 ALOGE("captureLayers called with an invalid or removed parent");
5845 return NAME_NOT_FOUND;
5846 }
5847
5848 const int uid = IPCThreadState::self()->getCallingUid();
5849 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5850 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5851 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5852 return PERMISSION_DENIED;
5853 }
5854
5855 if (sourceCrop.width() <= 0) {
5856 crop.left = 0;
5857 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5858 }
5859
5860 if (sourceCrop.height() <= 0) {
5861 crop.top = 0;
5862 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5863 }
5864 reqWidth = crop.width() * frameScale;
5865 reqHeight = crop.height() * frameScale;
5866
5867 for (const auto& handle : excludeHandles) {
5868 sp<Layer> excludeLayer = fromHandle(handle);
5869 if (excludeLayer != nullptr) {
5870 excludeLayers.emplace(excludeLayer);
5871 } else {
5872 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5873 return NAME_NOT_FOUND;
5874 }
5875 }
5876 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005877
Chia-I Wu20261cb2018-08-23 12:55:44 -07005878 // really small crop or frameScale
5879 if (reqWidth <= 0) {
5880 reqWidth = 1;
5881 }
5882 if (reqHeight <= 0) {
5883 reqHeight = 1;
5884 }
5885
Robert Carr866455f2019-04-02 16:28:26 -07005886 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5887 auto traverseLayers = [parent, childrenOnly,
5888 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005889 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5890 if (!layer->isVisible()) {
5891 return;
Robert Carr578038f2018-03-09 12:25:24 -08005892 } else if (childrenOnly && layer == parent.get()) {
5893 return;
chaviwa76b2712017-09-20 12:02:26 -07005894 }
Robert Carr866455f2019-04-02 16:28:26 -07005895
5896 sp<Layer> p = layer;
5897 while (p != nullptr) {
5898 if (excludeLayers.count(p) != 0) {
5899 return;
5900 }
5901 p = p->getParent();
5902 }
5903
chaviwa76b2712017-09-20 12:02:26 -07005904 visitor(layer);
5905 });
5906 };
Robert Carr108b2c72019-04-02 16:32:58 -07005907
5908 bool outCapturedSecureLayers = false;
5909 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5910 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005911}
5912
5913status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5914 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005915 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005916 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005917 bool useIdentityTransform,
5918 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005919 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005920
Peiyong Lin0e003c92018-09-17 11:09:51 -07005921 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005922 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5923 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005924 *outBuffer =
5925 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5926 static_cast<android_pixel_format>(reqPixelFormat), 1,
5927 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005928
Robert Carr108b2c72019-04-02 16:32:58 -07005929 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5930 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005931}
5932
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005933status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5934 TraverseLayersFunction traverseLayers,
5935 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005936 bool useIdentityTransform,
5937 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005938 // This mutex protects syncFd and captureResult for communication of the return values from the
5939 // main thread back to this Binder thread
5940 std::mutex captureMutex;
5941 std::condition_variable captureCondition;
5942 std::unique_lock<std::mutex> captureLock(captureMutex);
5943 int syncFd = -1;
5944 std::optional<status_t> captureResult;
5945
Robert Carr03480e22018-01-04 16:02:06 -08005946 const int uid = IPCThreadState::self()->getCallingUid();
5947 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5948
Dominik Laskowski8c001672018-05-30 16:52:06 -07005949 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005950 // If there is a refresh pending, bug out early and tell the binder thread to try again
5951 // after the refresh.
5952 if (mRefreshPending) {
5953 ATRACE_NAME("Skipping screenshot for now");
5954 std::unique_lock<std::mutex> captureLock(captureMutex);
5955 captureResult = std::make_optional<status_t>(EAGAIN);
5956 captureCondition.notify_one();
5957 return;
5958 }
5959
5960 status_t result = NO_ERROR;
5961 int fd = -1;
5962 {
5963 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005964 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005965 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005966 useIdentityTransform, forSystem, &fd,
5967 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005968 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005969 }
5970
5971 {
5972 std::unique_lock<std::mutex> captureLock(captureMutex);
5973 syncFd = fd;
5974 captureResult = std::make_optional<status_t>(result);
5975 captureCondition.notify_one();
5976 }
5977 });
5978
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005979 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005980 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005981 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005982 while (*captureResult == EAGAIN) {
5983 captureResult.reset();
5984 result = postMessageAsync(message);
5985 if (result != NO_ERROR) {
5986 return result;
5987 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005988 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005989 }
5990 result = *captureResult;
5991 }
5992
5993 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005994 sync_wait(syncFd, -1);
5995 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005996 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005997
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005998 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005999}
6000
chaviwa76b2712017-09-20 12:02:26 -07006001void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07006002 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006003 ANativeWindowBuffer* buffer, bool useIdentityTransform,
6004 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006005 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006006
chaviwa76b2712017-09-20 12:02:26 -07006007 const auto reqWidth = renderArea.getReqWidth();
6008 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006009 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006010 const auto transform = renderArea.getTransform();
6011 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006012
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006013 renderengine::DisplaySettings clientCompositionDisplay;
6014 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006015
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006016 // assume that bounds are never offset, and that they are the same as the
6017 // buffer bounds.
6018 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006019 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006020 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006021
6022 // Now take into account the rotation flag. We append a transform that
6023 // rotates the layer stack about the origin, then translate by buffer
6024 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006025 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006026 int displacementX = 0;
6027 int displacementY = 0;
6028 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6029 switch (rotation) {
6030 case ui::Transform::ROT_90:
6031 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006032 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006033 break;
6034 case ui::Transform::ROT_180:
6035 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006036 displacementY = renderArea.getBounds().getWidth();
6037 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006038 break;
6039 case ui::Transform::ROT_270:
6040 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006041 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006042 break;
6043 default:
6044 break;
6045 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006046
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006047 // We need to transform the clipping window into the right spot.
6048 // First, rotate the clipping rectangle by the rotation hint to get the
6049 // right orientation
6050 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6051 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6052 const vec4 rotClipTL = rotMatrix * clipTL;
6053 const vec4 rotClipBR = rotMatrix * clipBR;
6054 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6055 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6056 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6057 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6058
6059 // Now reposition the clipping rectangle with the displacement vector
6060 // computed above.
6061 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006062 clientCompositionDisplay.clip =
6063 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6064 newClipRight + displacementX, newClipBottom + displacementY);
6065
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006066 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006067 clientCompositionDisplay.globalTransform =
6068 clipTransform * clientCompositionDisplay.globalTransform;
6069
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006070 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6071 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006072
chaviw50da5042018-04-09 13:49:37 -07006073 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006074
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006075 renderengine::LayerSettings fillLayer;
6076 fillLayer.source.buffer.buffer = nullptr;
6077 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6078 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6079 fillLayer.alpha = half(alpha);
6080 clientCompositionLayers.push_back(fillLayer);
6081
6082 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006083 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006084 renderengine::LayerSettings layerSettings;
6085 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006086 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006087 if (prepared) {
6088 clientCompositionLayers.push_back(layerSettings);
6089 }
chaviwa76b2712017-09-20 12:02:26 -07006090 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006091
6092 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006093 // Use an empty fence for the buffer fence, since we just created the buffer so
6094 // there is no need for synchronization with the GPU.
6095 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006096 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006097 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006098 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006099 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006100
6101 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006102}
6103
chaviwa76b2712017-09-20 12:02:26 -07006104status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6105 TraverseLayersFunction traverseLayers,
6106 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006107 bool useIdentityTransform, bool forSystem,
6108 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006109 ATRACE_CALL();
6110
chaviwa76b2712017-09-20 12:02:26 -07006111 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006112 outCapturedSecureLayers =
6113 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006114 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006115
Robert Carr03480e22018-01-04 16:02:06 -08006116 // We allow the system server to take screenshots of secure layers for
6117 // use in situations like the Screen-rotation animation and place
6118 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006119 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006120 ALOGW("FB is protected: PERMISSION_DENIED");
6121 return PERMISSION_DENIED;
6122 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006123 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006124 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006125}
6126
chaviw95ef3c42019-02-14 10:55:09 -08006127void SurfaceFlinger::setInputWindowsFinished() {
6128 Mutex::Autolock _l(mStateLock);
6129
6130 mPendingSyncInputWindows = false;
6131 mTransactionCV.broadcast();
6132}
chaviw5f21a5e2019-02-14 10:00:34 -08006133
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006134// ---------------------------------------------------------------------------
6135
Dan Stoza412903f2017-04-27 13:42:17 -07006136void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6137 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006138}
6139
Dan Stoza412903f2017-04-27 13:42:17 -07006140void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6141 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006142}
6143
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006144void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006145 const LayerVector::Visitor& visitor) {
6146 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006147 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006148 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006149 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006150 continue;
6151 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006152 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006153 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006154 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006155 return;
6156 }
chaviwa76b2712017-09-20 12:02:26 -07006157 if (!layer->isVisible()) {
6158 return;
6159 }
6160 visitor(layer);
6161 });
6162 }
6163}
6164
Dominik Laskowski22488f62019-03-28 09:53:04 -07006165void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6166 const std::vector<int32_t>& allowedConfigs) {
6167 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006168 return;
6169 }
6170
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006171 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
6172 allowedConfigs.end());
6173 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
6174 return;
6175 }
6176
Ady Abraham838de062019-02-04 10:24:03 -08006177 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006178 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
6179
6180 // TODO(b/140204874): This hack triggers a notification that something has changed, so
6181 // that listeners that care about a change in allowed configs can get the notification.
6182 // Giving current ActiveConfig so that most other listeners would just drop the event
6183 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
6184 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08006185
Steven Thomase9eb1832019-08-28 16:08:35 -07006186 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
6187 // Set the highest allowed config by iterating backwards on available refresh rates
6188 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
6189 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
6190 if (isDisplayConfigAllowed(iter->second.configId)) {
6191 ALOGV("switching to allowed config %d", iter->second.configId);
6192 setDesiredActiveConfig(
6193 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
6194 break;
6195 }
Ady Abraham97d04232019-03-05 19:48:12 -08006196 }
Steven Thomase9eb1832019-08-28 16:08:35 -07006197 } else if (!isDisplayConfigAllowed(display->getActiveConfig())) {
6198 ALOGV("switching to config %d", allowedConfigs[0]);
6199 setDesiredActiveConfig(
6200 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
Ady Abraham97d04232019-03-05 19:48:12 -08006201 }
Ady Abraham838de062019-02-04 10:24:03 -08006202}
6203
Dominik Laskowski22488f62019-03-28 09:53:04 -07006204status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006205 const std::vector<int32_t>& allowedConfigs) {
6206 ATRACE_CALL();
6207
Dominik Laskowski22488f62019-03-28 09:53:04 -07006208 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006209 return BAD_VALUE;
6210 }
6211
Ady Abraham34392f72019-04-10 11:29:27 -07006212 if (mDebugDisplayConfigSetByBackdoor) {
6213 // ignore this request as config is overridden by backdoor
6214 return NO_ERROR;
6215 }
6216
Ady Abrahamabf91062019-10-18 14:17:23 -07006217 postMessageSync(new LambdaMessage([&]() {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006218 const auto display = getDisplayDeviceLocked(displayToken);
6219 if (!display) {
6220 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6221 displayToken.get());
6222 } else if (display->isVirtual()) {
6223 ALOGW("Attempt to set allowed display configs for virtual display");
6224 } else {
Ady Abrahamabf91062019-10-18 14:17:23 -07006225 Mutex::Autolock lock(mStateLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006226 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6227 }
Ady Abraham838de062019-02-04 10:24:03 -08006228 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006229
Ady Abraham838de062019-02-04 10:24:03 -08006230 return NO_ERROR;
6231}
6232
Dominik Laskowski22488f62019-03-28 09:53:04 -07006233status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006234 std::vector<int32_t>* outAllowedConfigs) {
6235 ATRACE_CALL();
6236
Dominik Laskowski22488f62019-03-28 09:53:04 -07006237 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006238 return BAD_VALUE;
6239 }
6240
Dominik Laskowski22488f62019-03-28 09:53:04 -07006241 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006242
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006243 const auto display = getDisplayDeviceLocked(displayToken);
6244 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006245 return NAME_NOT_FOUND;
6246 }
6247
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006248 if (display->isPrimary()) {
6249 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6250 }
6251
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006252 return NO_ERROR;
6253}
6254
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006255void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006256 mFlinger->setInputWindowsFinished();
6257}
6258
Robert Carrc0df3122019-04-11 13:18:21 -07006259sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6260 BBinder *b = handle->localBinder();
6261 if (b == nullptr) {
6262 return nullptr;
6263 }
6264 auto it = mLayersByLocalBinderToken.find(b);
6265 if (it != mLayersByLocalBinderToken.end()) {
6266 return it->second.promote();
6267 }
6268 return nullptr;
6269}
6270
Alec Mouri4545a8a2019-08-08 20:05:32 -07006271void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6272 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6273}
6274
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006275} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006276
Mathias Agopian3f844832013-08-07 21:24:32 -07006277#if defined(__gl_h_)
6278#error "don't include gl/gl.h in this file"
6279#endif
6280
6281#if defined(__gl2_h_)
6282#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006283#endif