blob: 30b380183d736dd371b1b860e342c77ba41aba01 [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
Ady Abraham97d04232019-03-05 19:48:12 -0800572 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700573 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700574 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800575
Dominik Laskowski22488f62019-03-28 09:53:04 -0700576 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Chaojiang Luo36e28ca2020-03-11 19:53:41 +0800577 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::Changed);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800578 } else {
Chaojiang Luo36e28ca2020-03-11 19:53:41 +0800579 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::Changed);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800580 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800581 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800582}
583
Dan Stoza436ccf32018-06-21 12:10:12 -0700584uint32_t SurfaceFlinger::getNewTexture() {
585 {
586 std::lock_guard lock(mTexturePoolMutex);
587 if (!mTexturePool.empty()) {
588 uint32_t name = mTexturePool.back();
589 mTexturePool.pop_back();
590 ATRACE_INT("TexturePoolSize", mTexturePool.size());
591 return name;
592 }
593
594 // The pool was too small, so increase it for the future
595 ++mTexturePoolSize;
596 }
597
598 // The pool was empty, so we need to get a new texture name directly using a
599 // blocking call to the main thread
600 uint32_t name = 0;
601 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
602 return name;
603}
604
Mathias Agopian3f844832013-08-07 21:24:32 -0700605void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700606 std::lock_guard lock(mTexturePoolMutex);
607 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
608 // to actually delete this or not based on mTexturePoolSize
609 mTexturePool.push_back(texture);
610 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700611}
612
Wei Wangf9b05ee2017-07-19 20:59:39 -0700613// Do not call property_set on main thread which will be blocked by init
614// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700615void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700616 ALOGI( "SurfaceFlinger's main thread ready to run. "
617 "Initializing graphics H/W...");
618
Ana Krulec757f63a2019-01-25 10:46:18 -0800619 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900620
Steven Thomasb02664d2017-07-26 18:48:28 -0700621 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700622 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800623 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700624 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
625 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800626 auto resyncCallback =
627 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800628
Ana Krulecc2870422019-01-29 19:00:58 -0800629 mAppConnectionHandle =
Ady Abraham45e4e362019-06-07 18:20:51 -0700630 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
631 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800632 resyncCallback,
633 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700634 mSfConnectionHandle =
635 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
636 mPhaseOffsets->getOffsetThresholdForNextVsync(),
637 resyncCallback, [this](nsecs_t timestamp) {
638 mInterceptor->saveVSyncEvent(timestamp);
639 });
Ana Krulecc2870422019-01-29 19:00:58 -0800640
641 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
642 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
643 mSfConnectionHandle.get());
644
Kevin DuBois413287f2019-02-25 08:46:47 -0800645 mRegionSamplingThread =
646 new RegionSamplingThread(*this, *mScheduler,
647 RegionSamplingThread::EnvironmentTimingTunables());
648
Steven Thomasb02664d2017-07-26 18:48:28 -0700649 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700650 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700651 renderEngineFeature |= (useColorManagement ?
652 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700653 renderEngineFeature |= (useContextPriority ?
654 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700655 renderEngineFeature |=
656 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
657 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700658
659 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800660 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700661 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700662 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800663 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700664
665 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
666 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700667 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
668 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800669 // Process any initial hotplug and resulting display changes.
670 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700671 const auto display = getDefaultDisplayDeviceLocked();
672 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700673 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700674 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800675
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700677 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700678 // This callback is called from the vr flinger dispatch thread. We
679 // need to call signalTransaction(), which requires holding
680 // mStateLock when we're not on the main thread. Acquiring
681 // mStateLock from the vr flinger dispatch thread might trigger a
682 // deadlock in surface flinger (see b/66916578), so post a message
683 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700684 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700685 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
686 mVrFlingerRequestsDisplay = requestDisplay;
687 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800689 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700690 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
691 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700692 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 .value_or(0),
694 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800695 if (!mVrFlinger) {
696 ALOGE("Failed to start vrflinger");
697 }
698 }
699
Mathias Agopian92a979a2012-08-02 18:32:23 -0700700 // initialize our drawing state
701 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700702
Andy McFadden13a082e2012-08-24 10:16:42 -0700703 // set initial conditions (e.g. unblank default device)
704 initializeDisplays();
705
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700706 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700707
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700709
710 const bool presentFenceReliable =
711 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
712 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700713
714 if (mStartPropertySetThread->Start() != NO_ERROR) {
715 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800716 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800717
Alec Mouri93bc83d2019-04-17 14:47:43 -0700718 mScheduler->setChangeRefreshRateCallback(
719 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
720 Mutex::Autolock lock(mStateLock);
721 setRefreshRateTo(type, event);
722 });
Alec Mouri7f015182019-07-11 13:56:22 -0700723 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
724 Mutex::Autolock lock(mStateLock);
725 const auto display = getDefaultDisplayDeviceLocked();
726 if (!display) {
727 // If we don't have a default display the fallback to the default
728 // refresh rate type
729 return RefreshRateType::DEFAULT;
730 }
731
732 const int configId = display->getActiveConfig();
733 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
734 if (refresh && refresh->configId == configId) {
735 return type;
736 }
737 }
738 // This should never happen, but just gracefully fallback to default.
739 return RefreshRateType::DEFAULT;
740 });
Alec Mouridc28b372019-04-18 21:17:13 -0700741 mScheduler->setGetVsyncPeriodCallback([this] {
742 Mutex::Autolock lock(mStateLock);
743 return getVsyncPeriod();
744 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700745
Dominik Laskowski22488f62019-03-28 09:53:04 -0700746 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
747 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800748
Dan Stoza9e56aa02015-11-02 13:00:03 -0800749 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700750}
751
Romain Guy11d63f42017-07-20 12:47:14 -0700752void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 Mutex::Autolock _l(mStateLock);
754
Romain Guy11d63f42017-07-20 12:47:14 -0700755 char value[PROPERTY_VALUE_MAX];
756
757 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800758 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700759 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800760 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100761
762 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700763 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800764
765 property_get("persist.sys.sf.color_mode", value, "0");
766 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700767}
768
Mathias Agopiana67e4182012-06-19 17:26:12 -0700769void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800770 // Start boot animation service by setting a property mailbox
771 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700772 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800773 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700774 if (mStartPropertySetThread->join() != NO_ERROR) {
775 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800776 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700777}
778
Mathias Agopian875d8e12013-06-07 15:35:48 -0700779size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700780 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700781}
782
Mathias Agopian875d8e12013-06-07 15:35:48 -0700783size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700784 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700785}
786
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800787// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800788
Jamie Gennis582270d2011-08-17 18:19:00 -0700789bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800790 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800791 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800792 return authenticateSurfaceTextureLocked(bufferProducer);
793}
794
795bool SurfaceFlinger::authenticateSurfaceTextureLocked(
796 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800797 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800798 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800799}
800
Brian Anderson6b376712017-04-04 10:51:39 -0700801status_t SurfaceFlinger::getSupportedFrameTimestamps(
802 std::vector<FrameEvent>* outSupported) const {
803 *outSupported = {
804 FrameEvent::REQUESTED_PRESENT,
805 FrameEvent::ACQUIRE,
806 FrameEvent::LATCH,
807 FrameEvent::FIRST_REFRESH_START,
808 FrameEvent::LAST_REFRESH_START,
809 FrameEvent::GPU_COMPOSITION_DONE,
810 FrameEvent::DEQUEUE_READY,
811 FrameEvent::RELEASE,
812 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700813 ConditionalLock _l(mStateLock,
814 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700815 if (!getHwComposer().hasCapability(
816 HWC2::Capability::PresentFenceIsNotReliable)) {
817 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
818 }
819 return NO_ERROR;
820}
821
Dominik Laskowski22488f62019-03-28 09:53:04 -0700822status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
823 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700824 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 return BAD_VALUE;
826 }
827
Dominik Laskowski22488f62019-03-28 09:53:04 -0700828 Mutex::Autolock lock(mStateLock);
829
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800830 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700831 if (!displayId) {
832 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700833 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834
Mathias Agopian8b736f12012-08-13 17:54:26 -0700835 // TODO: Not sure if display density should handled by SF any longer
836 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700839 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800840 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700841 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 }
843 return density;
844 }
845 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700846 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700847 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700848 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700849 return getDensityFromProperty("ro.sf.lcd_density"); }
850 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700853
Dominik Laskowski075d3172018-05-24 15:50:06 -0700854 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 DisplayInfo info = DisplayInfo();
856
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857 float xdpi = hwConfig->getDpiX();
858 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700859
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700860 info.w = hwConfig->getWidth();
861 info.h = hwConfig->getHeight();
862 // Default display viewport to display width and height
863 info.viewportW = info.w;
864 info.viewportH = info.h;
865
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800866 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700867 // The density of the device is provided by a build property
868 float density = Density::getBuildDensity() / 160.0f;
869 if (density == 0) {
870 // the build doesn't provide a density -- this is wrong!
871 // use xdpi instead
872 ALOGE("ro.sf.lcd_density must be defined as a build property");
873 density = xdpi / 160.0f;
874 }
875 if (Density::getEmuDensity()) {
876 // if "qemu.sf.lcd_density" is specified, it overrides everything
877 xdpi = ydpi = density = Density::getEmuDensity();
878 density /= 160.0f;
879 }
880 info.density = density;
881
882 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700883 const auto display = getDefaultDisplayDeviceLocked();
884 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700885
886 // This is for screenrecord
887 const Rect viewport = display->getViewport();
888 if (viewport.isValid()) {
889 info.viewportW = uint32_t(viewport.getWidth());
890 info.viewportH = uint32_t(viewport.getHeight());
891 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 } else {
893 // TODO: where should this value come from?
894 static const int TV_DENSITY = 213;
895 info.density = TV_DENSITY / 160.0f;
896 info.orientation = 0;
897 }
898
Dan Stoza7f7da322014-05-02 15:26:25 -0700899 info.xdpi = xdpi;
900 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700902 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
903 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
904 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800905
Andy McFadden91b2ca82014-06-13 14:04:23 -0700906 // This is how far in advance a buffer must be queued for
907 // presentation at a given time. If you want a buffer to appear
908 // on the screen at time N, you must submit the buffer before
909 // (N - presentationDeadline).
910 //
911 // Normally it's one full refresh period (to give SF a chance to
912 // latch the buffer), but this can be reduced by configuring a
913 // DispSync offset. Any additional delays introduced by the hardware
914 // composer or panel must be accounted for here.
915 //
916 // We add an additional 1ms to allow for processing time and
917 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700918 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700919
920 // All non-virtual displays are currently considered secure.
921 info.secure = true;
922
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800923 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700924 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800925 std::swap(info.w, info.h);
926 }
927
Michael Wright28f24d02016-07-12 13:30:53 -0700928 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700929 }
930
Dan Stoza7f7da322014-05-02 15:26:25 -0700931 return NO_ERROR;
932}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
935 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700936 return BAD_VALUE;
937 }
938
Ana Krulecc2870422019-01-29 19:00:58 -0800939 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700940 return NO_ERROR;
941}
942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
944 const auto display = getDisplayDevice(displayToken);
945 if (!display) {
946 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800947 return BAD_VALUE;
948 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700951}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700952
Ady Abraham03b02dd2019-03-21 15:40:11 -0700953void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800955
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800957 // config twice. However event generation config might have changed so we need to update it
958 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800959 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700960 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
961 mDesiredActiveConfig = info;
962 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963
964 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800965 // This will trigger HWC refresh without resetting the idle timer.
966 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700967 // Start receiving vsync samples now, so that we can detect a period
968 // switch.
969 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700970 // As we called to set period, we will call to onRefreshRateChangeCompleted once
971 // DispSync model is locked.
972 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700973 mPhaseOffsets->setRefreshRateType(info.type);
974 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700975 mVsyncModulator.setPhaseOffsets(early, gl, late,
976 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 mDesiredActiveConfigChanged = true;
979 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700980
981 if (mRefreshRateOverlay) {
982 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
983 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800984}
985
986status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
987 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800988
989 std::vector<int32_t> allowedConfig;
990 allowedConfig.push_back(mode);
991
992 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800993}
994
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995void SurfaceFlinger::setActiveConfigInternal() {
996 ATRACE_CALL();
997
Dominik Laskowski22488f62019-03-28 09:53:04 -0700998 const auto display = getDefaultDisplayDeviceLocked();
999 if (!display) {
1000 return;
1001 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002
Dominik Laskowski22488f62019-03-28 09:53:04 -07001003 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1004 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
1005
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001006 display->setActiveConfig(mUpcomingActiveConfig.configId);
1007
Alec Mouri754c98a2019-03-18 18:53:42 -07001008 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001009 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001010 mVsyncModulator.setPhaseOffsets(early, gl, late,
1011 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001013
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001014 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001015 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1016 mUpcomingActiveConfig.configId);
1017 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001018}
1019
Ady Abraham53852a52019-05-28 18:07:44 -07001020void SurfaceFlinger::desiredActiveConfigChangeDone() {
1021 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1022 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1023 mDesiredActiveConfigChanged = false;
1024 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1025
1026 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1027 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
1028 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001029 mVsyncModulator.setPhaseOffsets(early, gl, late,
1030 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -07001031}
1032
Dominik Laskowski22488f62019-03-28 09:53:04 -07001033bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001034 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001035 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001036 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001038 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039 return true;
1040 }
1041
1042 // We received the present fence from the HWC, so we assume it successfully updated
1043 // the config, hence we update SF.
1044 mCheckPendingFence = false;
1045 setActiveConfigInternal();
1046 }
1047
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001048 // Store the local variable to release the lock.
1049 ActiveConfigInfo desiredActiveConfig;
1050 {
1051 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001052 if (!mDesiredActiveConfigChanged) {
1053 return false;
1054 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001055 desiredActiveConfig = mDesiredActiveConfig;
1056 }
1057
Dominik Laskowski22488f62019-03-28 09:53:04 -07001058 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001059 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1060 // display is not valid or we are already in the requested mode
1061 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001062 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001063 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001064 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001065
Ady Abraham838de062019-02-04 10:24:03 -08001066 // Desired active config was set, it is different than the config currently in use, however
1067 // allowed configs might have change by the time we process the refresh.
1068 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001069 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001070 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001071 return false;
1072 }
Alec Mouri7f015182019-07-11 13:56:22 -07001073
Ady Abrahamb838aed2019-02-12 15:30:16 -08001074 mUpcomingActiveConfig = desiredActiveConfig;
1075 const auto displayId = display->getId();
1076 LOG_ALWAYS_FATAL_IF(!displayId);
1077
1078 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1079 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1080
1081 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001082 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001083 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001084 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001085}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001086
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1088 Vector<ColorMode>* outColorModes) {
1089 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001090 return BAD_VALUE;
1091 }
1092
Peiyong Lina52f0292018-03-14 17:26:31 -07001093 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001094 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001095 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001096 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1097
1098 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1099 if (!displayId) {
1100 return NAME_NOT_FOUND;
1101 }
1102
Dominik Laskowski075d3172018-05-24 15:50:06 -07001103 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001104 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001105 }
Michael Wright28f24d02016-07-12 13:30:53 -07001106 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001107
1108 // If it's built-in display and the configuration claims it's not wide color capable,
1109 // filter out all wide color modes. The typical reason why this happens is that the
1110 // hardware is not good enough to support GPU composition of wide color, and thus the
1111 // OEMs choose to disable this capability.
1112 if (isInternalDisplay && !hasWideColorDisplay) {
1113 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1114 isWideColorMode);
1115 } else {
1116 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1117 }
Michael Wright28f24d02016-07-12 13:30:53 -07001118
1119 return NO_ERROR;
1120}
1121
Daniel Solomon42d04562019-01-20 21:03:19 -08001122status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1123 ui::DisplayPrimaries &primaries) {
1124 if (!displayToken) {
1125 return BAD_VALUE;
1126 }
1127
1128 // Currently we only support this API for a single internal display.
1129 if (getInternalDisplayToken() != displayToken) {
1130 return BAD_VALUE;
1131 }
1132
1133 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1134 return NO_ERROR;
1135}
1136
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001137ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1138 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001139 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001140 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001141 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001142}
1143
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001144status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001145 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 Vector<ColorMode> modes;
1147 getDisplayColorModes(displayToken, &modes);
1148 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1149 if (mode < ColorMode::NATIVE || !exists) {
1150 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1151 decodeColorMode(mode).c_str(), mode, displayToken.get());
1152 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001153 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001154 const auto display = getDisplayDevice(displayToken);
1155 if (!display) {
1156 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1157 decodeColorMode(mode).c_str(), mode, displayToken.get());
1158 } else if (display->isVirtual()) {
1159 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1160 decodeColorMode(mode).c_str(), mode);
1161 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001162 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1163 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001164 }
1165 }));
1166
Michael Wright28f24d02016-07-12 13:30:53 -07001167 return NO_ERROR;
1168}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001169
Svetoslavd85084b2014-03-20 10:28:31 -07001170status_t SurfaceFlinger::clearAnimationFrameStats() {
1171 Mutex::Autolock _l(mStateLock);
1172 mAnimFrameTracker.clearStats();
1173 return NO_ERROR;
1174}
1175
1176status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1177 Mutex::Autolock _l(mStateLock);
1178 mAnimFrameTracker.getStats(outStats);
1179 return NO_ERROR;
1180}
1181
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001182status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1183 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001184 Mutex::Autolock _l(mStateLock);
1185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001186 const auto display = getDisplayDeviceLocked(displayToken);
1187 if (!display) {
1188 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001189 return BAD_VALUE;
1190 }
1191
Peiyong Linfb069302018-04-25 14:34:31 -07001192 // At this point the DisplayDeivce should already be set up,
1193 // meaning the luminance information is already queried from
1194 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001195 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001196 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1197 capabilities.getDesiredMaxLuminance(),
1198 capabilities.getDesiredMaxAverageLuminance(),
1199 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001200
1201 return NO_ERROR;
1202}
1203
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001204status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1205 ui::PixelFormat* outFormat,
1206 ui::Dataspace* outDataspace,
1207 uint8_t* outComponentMask) const {
1208 if (!outFormat || !outDataspace || !outComponentMask) {
1209 return BAD_VALUE;
1210 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001211 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001212 if (!display || !display->getId()) {
1213 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1214 return BAD_VALUE;
1215 }
1216 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1217 outDataspace, outComponentMask);
1218}
1219
Kevin DuBois74e53772018-11-19 10:52:38 -08001220status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1221 bool enable, uint8_t componentMask,
1222 uint64_t maxFrames) const {
1223 const auto display = getDisplayDevice(displayToken);
1224 if (!display || !display->getId()) {
1225 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1226 return BAD_VALUE;
1227 }
1228
1229 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1230 componentMask, maxFrames);
1231}
1232
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001233status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1234 uint64_t maxFrames, uint64_t timestamp,
1235 DisplayedFrameStats* outStats) const {
1236 const auto display = getDisplayDevice(displayToken);
1237 if (!display || !display->getId()) {
1238 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1239 return BAD_VALUE;
1240 }
1241
1242 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1243 outStats);
1244}
1245
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001246status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1247 if (!outSupported) {
1248 return BAD_VALUE;
1249 }
1250 *outSupported = getRenderEngine().supportsProtectedContent();
1251 return NO_ERROR;
1252}
1253
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001254status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1255 bool* outIsWideColorDisplay) const {
1256 if (!displayToken || !outIsWideColorDisplay) {
1257 return BAD_VALUE;
1258 }
1259 Mutex::Autolock _l(mStateLock);
1260 const auto display = getDisplayDeviceLocked(displayToken);
1261 if (!display) {
1262 return BAD_VALUE;
1263 }
Peiyong Linff84a152019-05-17 18:36:19 -07001264
1265 // Use hasWideColorDisplay to override built-in display.
1266 const auto displayId = display->getId();
1267 if (displayId && displayId == getInternalDisplayIdLocked()) {
1268 *outIsWideColorDisplay = hasWideColorDisplay;
1269 return NO_ERROR;
1270 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001271 *outIsWideColorDisplay = display->hasWideColorGamut();
1272 return NO_ERROR;
1273}
1274
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001275status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001276 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001277 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001278
Chia-I Wu90f669f2017-10-05 14:24:41 -07001279 if (mInjectVSyncs == enable) {
1280 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001281 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001282
Ana Krulecc2870422019-01-29 19:00:58 -08001283 auto resyncCallback =
1284 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001285
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001286 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001287 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001288 if (enable) {
1289 ALOGV("VSync Injections enabled");
1290 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001291 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001292 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001293 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001294 impl::EventThread::InterceptVSyncsCallback(),
1295 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001296 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001297 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001298 } else {
1299 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001300 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1301 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001302 }
1303
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001304 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001305 }));
1306
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001307 return NO_ERROR;
1308}
1309
1310status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001311 Mutex::Autolock _l(mStateLock);
1312
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001313 if (!mInjectVSyncs) {
1314 ALOGE("VSync Injections not enabled");
1315 return BAD_VALUE;
1316 }
1317 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1318 ALOGV("Injecting VSync inside SurfaceFlinger");
1319 mVSyncInjector->onInjectSyncEvent(when);
1320 }
1321 return NO_ERROR;
1322}
1323
Lloyd Pique755e3192018-01-31 16:46:15 -08001324status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1325 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001326 // Try to acquire a lock for 1s, fail gracefully
1327 const status_t err = mStateLock.timedLock(s2ns(1));
1328 const bool locked = (err == NO_ERROR);
1329 if (!locked) {
1330 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1331 return TIMED_OUT;
1332 }
1333
1334 outLayers->clear();
1335 mCurrentState.traverseInZOrder([&](Layer* layer) {
1336 outLayers->push_back(layer->getLayerDebugInfo());
1337 });
1338
1339 mStateLock.unlock();
1340 return NO_ERROR;
1341}
1342
Peiyong Linc6780972018-10-28 15:24:08 -07001343status_t SurfaceFlinger::getCompositionPreference(
1344 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1345 Dataspace* outWideColorGamutDataspace,
1346 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001347 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001348 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001349 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001350 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001351 return NO_ERROR;
1352}
1353
Dan Stozaec460082018-12-17 15:35:09 -08001354status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1355 const sp<IBinder>& stopLayerHandle,
1356 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001357 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001358 return BAD_VALUE;
1359 }
1360 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001361 return NO_ERROR;
1362}
1363
Dan Stozaec460082018-12-17 15:35:09 -08001364status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001365 if (!listener) {
1366 return BAD_VALUE;
1367 }
Dan Stozaec460082018-12-17 15:35:09 -08001368 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001369 return NO_ERROR;
1370}
Dan Gittik57e63c52019-01-18 16:37:54 +00001371
1372status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1373 bool* outSupport) const {
1374 if (!displayToken || !outSupport) {
1375 return BAD_VALUE;
1376 }
1377 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1378 if (!displayId) {
1379 return NAME_NOT_FOUND;
1380 }
1381 *outSupport =
1382 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1383 return NO_ERROR;
1384}
1385
1386status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1387 float brightness) const {
1388 if (!displayToken) {
1389 return BAD_VALUE;
1390 }
1391 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1392 if (!displayId) {
1393 return NAME_NOT_FOUND;
1394 }
1395 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1396}
1397
Ady Abraham8532d012019-05-08 14:50:56 -07001398status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1399 PowerHint powerHint = static_cast<PowerHint>(hintId);
1400
1401 if (powerHint == PowerHint::INTERACTION) {
1402 mScheduler->notifyTouchEvent();
1403 }
1404
1405 return NO_ERROR;
1406}
1407
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001408// ----------------------------------------------------------------------------
1409
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001410sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001411 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001412 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001413 Mutex::Autolock lock(mStateLock);
1414 return getVsyncPeriod();
1415 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001416
Ana Krulecc2870422019-01-29 19:00:58 -08001417 const auto& handle =
1418 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001419
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001420 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1421 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001422}
1423
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001424// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001425
1426void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001427 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001428}
1429
1430void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001431 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001432 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001433}
1434
1435void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001436 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001437 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001438}
1439
1440void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001441 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001442 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001443}
1444
1445status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001446 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001447 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001448}
1449
1450status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001451 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001452 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001453 if (res == NO_ERROR) {
1454 msg->wait();
1455 }
1456 return res;
1457}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001459void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001460 do {
1461 waitForEvent();
1462 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001463}
1464
Dominik Laskowski83b88212018-12-11 13:34:06 -08001465nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001466 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001467 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1468 return 0;
1469 }
1470
1471 const auto config = getHwComposer().getActiveConfig(*displayId);
1472 return config ? config->getVsyncPeriod() : 0;
1473}
1474
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001475void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1476 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001477 ATRACE_NAME("SF onVsync");
1478
Steven Thomas3cfac282017-02-06 12:29:30 -08001479 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001481 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001482 return;
1483 }
1484
Dominik Laskowski075d3172018-05-24 15:50:06 -07001485 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001486 return;
1487 }
1488
Dominik Laskowski075d3172018-05-24 15:50:06 -07001489 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001490 // For now, we don't do anything with external display vsyncs.
1491 return;
1492 }
1493
Alec Mourif8e689c2019-05-20 18:32:22 -07001494 bool periodFlushed = false;
1495 mScheduler->addResyncSample(timestamp, &periodFlushed);
1496 if (periodFlushed) {
1497 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001498 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001499}
1500
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001501void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001502 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1503 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001504}
1505
Dominik Laskowski22488f62019-03-28 09:53:04 -07001506bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1507 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001508}
1509
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001510void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001511 const auto display = getDefaultDisplayDeviceLocked();
1512 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001513 return;
1514 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001515 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001516
Ana Krulec7d1d6832018-12-27 11:10:09 -08001517 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001518 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001519 if (!refreshRateConfig) {
1520 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001521 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001522 }
Ady Abraham1902d072019-03-01 17:18:59 -08001523
Alec Mouri0a1cc962019-03-14 12:33:02 -07001524 const int desiredConfigId = refreshRateConfig->configId;
1525
Dominik Laskowski22488f62019-03-28 09:53:04 -07001526 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001527 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1528 return;
1529 }
1530
Dominik Laskowski22488f62019-03-28 09:53:04 -07001531 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001532}
1533
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001534void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001535 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001536 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001537 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538
Lloyd Piqueba04e622017-12-14 17:11:26 -08001539 // Ignore events that do not have the right sequenceId.
1540 if (sequenceId != getBE().mComposerSequenceId) {
1541 return;
1542 }
1543
Steven Thomasb02664d2017-07-26 18:48:28 -07001544 // Only lock if we're not on the main thread. This function is normally
1545 // called on a hwbinder thread, but for the primary display it's called on
1546 // the main thread with the state lock already held, so don't attempt to
1547 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001548 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001549
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001550 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001551
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001552 if (std::this_thread::get_id() == mMainThreadId) {
1553 // Process all pending hot plug events immediately if we are on the main thread.
1554 processDisplayHotplugEventsLocked();
1555 }
1556
Lloyd Piqueba04e622017-12-14 17:11:26 -08001557 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001558}
1559
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001560void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001561 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001562 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001564 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001565 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001566}
1567
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001568void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001569 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001570
1571 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1572 // display power state.
1573 postMessageAsync(new LambdaMessage(
1574 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1575}
1576
1577void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1578 ATRACE_CALL();
1579
Ady Abraham27c70212019-06-11 10:52:26 -07001580 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1581
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001582 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001583 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1584 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001585 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001586 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001587 }
Mathias Agopian86303202012-07-24 22:46:10 -07001588}
1589
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001591void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001592 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593 // Clear the drawing state so that the logic inside of
1594 // handleTransactionLocked will fire. It will determine the delta between
1595 // mCurrentState and mDrawingState and re-apply all changes when we make the
1596 // transition.
1597 mDrawingState.displays.clear();
1598 mDisplays.clear();
1599}
1600
Steven Thomas050b2c82017-03-06 11:45:16 -08001601void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001602 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001603 if (!mVrFlinger)
1604 return;
1605 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001606 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001607 return;
1608 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001609
Lloyd Pique441d5042018-10-18 16:49:51 -07001610 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001611 ALOGE("Vr flinger is only supported for remote hardware composer"
1612 " service connections. Ignoring request to transition to vr"
1613 " flinger.");
1614 mVrFlingerRequestsDisplay = false;
1615 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001616 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001617
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001618 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001619
Steven Thomas0123ac62018-07-12 11:32:34 -07001620 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001621 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001622
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001623 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001624
1625 // Clear out all the output layers from the composition engine for all
1626 // displays before destroying the hardware composer interface. This ensures
1627 // any HWC layers are destroyed through that interface before it becomes
1628 // invalid.
1629 for (const auto& [token, displayDevice] : mDisplays) {
1630 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1631 compositionengine::Output::OutputLayers());
1632 }
1633
Steven Thomas0123ac62018-07-12 11:32:34 -07001634 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1635 // called below. Clear the reference now so we don't accidentally use it
1636 // later.
1637 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001638
Steven Thomasb02664d2017-07-26 18:48:28 -07001639 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001640 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001641 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001642
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001644 // Delete the current instance before creating the new one
1645 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1646 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1647 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1648 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001649
Lloyd Pique441d5042018-10-18 16:49:51 -07001650 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001651 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001652
1653 if (vrFlingerRequestsDisplay) {
1654 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001655 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001656
1657 mVisibleRegionsDirty = true;
1658 invalidateHwcGeometry();
1659
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001660 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001661 display = getDefaultDisplayDeviceLocked();
1662 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001663 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001664
Steven Thomasb02664d2017-07-26 18:48:28 -07001665 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001666 const nsecs_t vsyncPeriod = getVsyncPeriod();
1667 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001668
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001669 // The present fences returned from vr_hwc are not an accurate
1670 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001671 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001672
Steven Thomasb02664d2017-07-26 18:48:28 -07001673 // Use phase of 0 since phase is not known.
1674 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001675 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001676 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001677
Ana Krulecc2870422019-01-29 19:00:58 -08001678 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001679
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001680 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001681 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001682}
1683
Ady Abrahamb40b0262019-09-19 11:32:43 -07001684bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1685 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001686 // We are storing the last 2 present fences. If sf's phase offset is to be
1687 // woken up before the actual vsync but targeting the next vsync, we need to check
1688 // fence N-2
1689 const sp<Fence>& fence =
1690 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1691 ? mPreviousPresentFences[0]
1692 : mPreviousPresentFences[1];
1693
Ady Abrahamb40b0262019-09-19 11:32:43 -07001694 if (fence == Fence::NO_FENCE) {
1695 return false;
1696 }
1697
1698 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1699 fence->wait(graceTimeMs);
1700 }
1701
1702 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001703}
1704
Ady Abraham7c03ce62019-07-19 10:59:45 -07001705void SurfaceFlinger::populateExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
Alec Mouriaa614192019-06-06 13:28:34 -07001706 DisplayStatInfo stats;
1707 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001708 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001709 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham7c03ce62019-07-19 10:59:45 -07001710 mExpectedPresentTime =
Alec Mouriaa614192019-06-06 13:28:34 -07001711 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1712 ? presentTime
1713 : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001714}
1715
Dominik Laskowski22488f62019-03-28 09:53:04 -07001716void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001717 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001718 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001719 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001720 // calculate the expected present time once and use the cached
1721 // value throughout this frame to make sure all layers are
1722 // seeing this same value.
1723 populateExpectedPresentTime();
1724
Ady Abrahamb40b0262019-09-19 11:32:43 -07001725 // When Backpressure propagation is enabled we want to give a small grace period
1726 // for the present fence to fire instead of just giving up on this frame to handle cases
1727 // where present fence is just about to get signaled.
1728 const int graceTimeForPresentFenceMs =
1729 (mPropagateBackpressure &&
1730 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1731 ? 1
1732 : 0;
1733 bool frameMissed = previousFrameMissed(graceTimeForPresentFenceMs);
Alec Mouricc0fc602019-02-26 21:45:19 -08001734 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1735 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1736 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1737 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1738 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1739 if (frameMissed) {
1740 mFrameMissedCount++;
1741 mTimeStats->incrementMissedFrames();
1742 }
1743
Alec Mouri40189b02019-03-05 15:07:54 -08001744 if (hwcFrameMissed) {
1745 mHwcFrameMissedCount++;
1746 }
1747
1748 if (gpuFrameMissed) {
1749 mGpuFrameMissedCount++;
1750 }
1751
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001752 if (mUseSmart90ForVideo) {
1753 // This call is made each time SF wakes up and creates a new frame. It is part
1754 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001755 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001756 }
1757
Ady Abrahamb838aed2019-02-12 15:30:16 -08001758 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001759 break;
1760 }
1761
Ady Abrahamadb9a992019-09-19 21:21:55 +00001762 if (frameMissed && mPropagateBackpressure) {
1763 if ((hwcFrameMissed && !gpuFrameMissed) ||
1764 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001765 signalLayerUpdate();
1766 break;
1767 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001768 }
Dan Stoza50182882016-07-08 12:02:20 -07001769
Steven Thomas050b2c82017-03-06 11:45:16 -08001770 // Now that we're going to make it to the handleMessageTransaction()
1771 // call below it's safe to call updateVrFlinger(), which will
1772 // potentially trigger a display handoff.
1773 updateVrFlinger();
1774
Dan Stoza6b9454d2014-11-07 16:00:59 -08001775 bool refreshNeeded = handleMessageTransaction();
1776 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001777
1778 updateCursorAsync();
1779 updateInputFlinger();
1780
Dan Stoza58784442014-12-02 16:58:17 -08001781 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001782 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001783 // Signal a refresh if a transaction modified the window state,
1784 // a new buffer was latched, or if HWC has requested a full
1785 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001786 signalRefresh();
1787 }
1788 break;
1789 }
1790 case MessageQueue::REFRESH: {
1791 handleMessageRefresh();
1792 break;
1793 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001794 }
1795}
1796
Dan Stoza6b9454d2014-11-07 16:00:59 -08001797bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001798 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001799 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001800
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001801 bool flushedATransaction = flushTransactionQueues();
1802
1803 bool runHandleTransaction = transactionFlags &&
1804 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1805
1806 if (runHandleTransaction) {
1807 handleTransaction(eTransactionMask);
1808 } else {
1809 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001810 }
1811
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001812 if (transactionFlushNeeded()) {
1813 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001814 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001815
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001816 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001817}
1818
Mathias Agopian4fec8732012-06-29 14:12:52 -07001819void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001820 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001821
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001822 mRefreshPending = false;
1823
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001824 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001825 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001826 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001827 calculateWorkingSet();
Nataniel Borgesc4def152019-09-26 15:20:00 +02001828 long compositionTime = elapsedRealtimeNano();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001829 for (const auto& [token, display] : mDisplays) {
1830 beginFrame(display);
1831 prepareFrame(display);
1832 doDebugFlashRegions(display, repaintEverything);
1833 doComposition(display, repaintEverything);
1834 }
1835
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001836 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001837
1838 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001839 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001840
Dan Stozabfbffeb2016-07-21 14:49:33 -07001841 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001842 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001843 for (const auto& [token, displayDevice] : mDisplays) {
1844 auto display = displayDevice->getCompositionDisplay();
1845 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001846 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001847 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001848 mHadDeviceComposition =
1849 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001850 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001851
Jorim Jaggi90535212018-05-23 23:44:06 +02001852 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001853
David Sodman7e4ae112018-02-09 15:02:28 -08001854 mLayersWithQueuedFrames.clear();
Vishnu Nair6bfe2642019-06-07 14:53:14 -07001855 if (mVisibleRegionsDirty) {
1856 mVisibleRegionsDirty = false;
1857 if (mTracingEnabled) {
Nataniel Borgesc4def152019-09-26 15:20:00 +02001858 mTracing.notify(compositionTime, "visibleRegionsDirty");
Vishnu Nair6bfe2642019-06-07 14:53:14 -07001859 }
1860 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001861}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001862
David Sodmanfa9b2af2017-12-24 13:28:59 -08001863
1864bool SurfaceFlinger::handleMessageInvalidate() {
1865 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001866 bool refreshNeeded = handlePageFlip();
1867
Vishnu Nair4351ad52019-02-11 14:13:02 -08001868 if (mVisibleRegionsDirty) {
1869 computeLayerBounds();
1870 }
1871
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001872 for (auto& layer : mLayersPendingRefresh) {
1873 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001874 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001875 invalidateLayerStack(layer, visibleReg);
1876 }
1877 mLayersPendingRefresh.clear();
1878 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001879}
1880
David Sodman79bba0e2018-08-05 18:07:49 -07001881void SurfaceFlinger::calculateWorkingSet() {
1882 ATRACE_CALL();
1883 ALOGV(__FUNCTION__);
1884
David Sodman79bba0e2018-08-05 18:07:49 -07001885 // build the h/w work list
1886 if (CC_UNLIKELY(mGeometryInvalid)) {
1887 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001888 for (const auto& [token, displayDevice] : mDisplays) {
1889 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001890
Lloyd Piquea83776c2019-01-29 18:42:32 -08001891 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001892
Lloyd Piquea83776c2019-01-29 18:42:32 -08001893 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1894 auto& compositionState = layer->editState();
1895 compositionState.forceClientComposition = false;
1896 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1897 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001898 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001899
Lloyd Piquea83776c2019-01-29 18:42:32 -08001900 // The output Z order is set here based on a simple counter.
1901 compositionState.z = zOrder++;
1902
1903 // Update the display independent composition state. This goes
1904 // to the general composition layer state structure.
1905 // TODO: Do this once per compositionengine::CompositionLayer.
1906 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1907 true);
1908
1909 // Recalculate the geometry state of the output layer.
1910 layer->updateCompositionState(true);
1911
1912 // Write the updated geometry state to the HWC
1913 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001914 }
1915 }
1916 }
1917
1918 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001919 for (const auto& [token, displayDevice] : mDisplays) {
1920 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001921 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001922 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001923 continue;
1924 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001925 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001926
1927 if (mDrawingState.colorMatrixChanged) {
1928 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001929 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001930 Dataspace targetDataspace = Dataspace::UNKNOWN;
1931 if (useColorManagement) {
1932 ColorMode colorMode;
1933 RenderIntent renderIntent;
1934 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1935 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001936
1937 if (isHdrColorMode(colorMode)) {
1938 targetDataspace = Dataspace::UNKNOWN;
1939 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1940 targetDataspace = mColorSpaceAgnosticDataspace;
1941 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001942 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001943
Lloyd Pique32cbe282018-10-19 13:09:22 -07001944 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001945 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001946 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001947 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1948 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001949 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001950 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001951 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1952 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001953 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001954 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001955 }
1956
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001957 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001958 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001959 }
1960
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001961 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001962 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001963 layer->setCompositionType(displayDevice,
1964 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001965 continue;
1966 }
1967
Lloyd Pique32cbe282018-10-19 13:09:22 -07001968 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001969 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001970 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001971 }
1972 }
1973
1974 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001975
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001976 for (const auto& [token, displayDevice] : mDisplays) {
1977 auto display = displayDevice->getCompositionDisplay();
1978 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001979 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1980 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1981 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001982 }
1983 }
David Sodman79bba0e2018-08-05 18:07:49 -07001984}
1985
Lloyd Pique32cbe282018-10-19 13:09:22 -07001986void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1987 bool repaintEverything) {
1988 auto display = displayDevice->getCompositionDisplay();
1989 const auto& displayState = display->getState();
1990
Mathias Agopiancd60f992012-08-16 16:28:27 -07001991 // is debugging enabled
1992 if (CC_LIKELY(!mDebugRegion))
1993 return;
1994
Lloyd Pique32cbe282018-10-19 13:09:22 -07001995 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001996 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001997 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001998 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001999 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08002000 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002001 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002003 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07002004 }
2005 }
2006
Lloyd Pique32cbe282018-10-19 13:09:22 -07002007 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002008
2009 if (mDebugRegion > 1) {
2010 usleep(mDebugRegion * 1000);
2011 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07002012
Lloyd Pique32cbe282018-10-19 13:09:22 -07002013 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014}
2015
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002016void SurfaceFlinger::logLayerStats() {
2017 ATRACE_CALL();
2018 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002019 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002020 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002021 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002022 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002023 }
2024 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07002025
2026 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002027 }
2028}
2029
David Sodman2b406362017-12-15 13:33:47 -08002030void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002032 ATRACE_CALL();
2033 ALOGV("preComposition");
2034
David Sodman2b406362017-12-15 13:33:47 -08002035 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2036
Mathias Agopiancd60f992012-08-16 16:28:27 -07002037 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002038 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002039 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002040 needExtraInvalidate = true;
2041 }
Robert Carr2047fae2016-11-28 14:09:09 -08002042 });
2043
Mathias Agopiancd60f992012-08-16 16:28:27 -07002044 if (needExtraInvalidate) {
2045 signalLayerUpdate();
2046 }
2047}
2048
Ana Krulece588e312018-09-18 12:32:24 -07002049void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2050 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051 // Update queue of past composite+present times and determine the
2052 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002053 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002054 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002055 while (!getBE().mCompositePresentTimes.empty()) {
2056 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002057 // Cached values should have been updated before calling this method,
2058 // which helps avoid duplicate syscalls.
2059 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2060 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2061 break;
2062 }
2063 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002064 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002065 }
2066
2067 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002068 while (getBE().mCompositePresentTimes.size() > 16) {
2069 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002070 }
2071
Ana Krulece588e312018-09-18 12:32:24 -07002072 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002073}
2074
Ana Krulece588e312018-09-18 12:32:24 -07002075void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2076 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077 // Integer division and modulo round toward 0 not -inf, so we need to
2078 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002079 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2080 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2081 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002082
Ana Krulec757f63a2019-01-25 10:46:18 -08002083 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002084 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002085 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002086 }
2087
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002088 // Snap the latency to a value that removes scheduling jitter from the
2089 // composition and present times, which often have >1ms of jitter.
2090 // Reducing jitter is important if an app attempts to extrapolate
2091 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002092 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002093 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002094 nsecs_t bias = stats.vsyncPeriod / 2;
2095 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2096 nsecs_t snappedCompositeToPresentLatency =
2097 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002098
David Sodman99974d22017-11-28 12:04:33 -08002099 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002100 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2101 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002102 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002103}
2104
David Sodman2b406362017-12-15 13:33:47 -08002105void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002106{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002107 ATRACE_CALL();
2108 ALOGV("postComposition");
2109
Brian Anderson3546a3f2016-07-14 11:51:14 -07002110 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002111 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002112 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002113 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002114 }
2115
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002116 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002117 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002118
David Sodman73beded2017-11-15 11:56:06 -08002119 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002120 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002121 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002122 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002123 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2124 ->getRenderSurface()
2125 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002126 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002127 } else {
2128 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2129 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002130
David Sodman73beded2017-11-15 11:56:06 -08002131 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002132 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2133 mPreviousPresentFences[0] = displayDevice
2134 ? getHwComposer().getPresentFence(*displayDevice->getId())
2135 : Fence::NO_FENCE;
2136 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002137 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002138
Ana Krulece588e312018-09-18 12:32:24 -07002139 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002140 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002141
David Sodman2b406362017-12-15 13:33:47 -08002142 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002143 // when we started doing work for this frame, but that should be okay
2144 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002145 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002146 CompositorTiming compositorTiming;
2147 {
David Sodman99974d22017-11-28 12:04:33 -08002148 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2149 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002150 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002151
Robert Carr2047fae2016-11-28 14:09:09 -08002152 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002153 bool frameLatched =
2154 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2155 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002156 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002157 recordBufferingStats(layer->getName().string(),
2158 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002159 }
Robert Carr2047fae2016-11-28 14:09:09 -08002160 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002161
Valerie Hau7687b3c2020-04-15 18:09:40 -07002162 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2163
2164 // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
2165 // If we do not lock here, a callback could be sent without all of its SurfaceControls and
2166 // metrics.
2167 {
2168 Mutex::Autolock _l(mStateLock);
2169 mTransactionCompletedThread.sendCallbacks();
2170 }
2171
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002172 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002173 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002174 }
2175
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002176 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002177 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2178 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002179 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002180 }
2181 }
2182
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002183 if (mAnimCompositionPending) {
2184 mAnimCompositionPending = false;
2185
Brian Anderson4e606e32017-03-16 15:34:57 -07002186 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002187 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002188 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002189 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002190 // The HWC doesn't support present fences, so use the refresh
2191 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002192 const nsecs_t presentTime =
2193 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002194 mAnimFrameTracker.setActualPresentTime(presentTime);
2195 }
2196 mAnimFrameTracker.advanceFrame();
2197 }
Dan Stozab90cf072015-03-05 11:05:59 -08002198
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002199 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002200 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002201 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002202 }
2203
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002204 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002205
Lloyd Pique32cbe282018-10-19 13:09:22 -07002206 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2207 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002208 return;
2209 }
2210
2211 nsecs_t currentTime = systemTime();
2212 if (mHasPoweredOff) {
2213 mHasPoweredOff = false;
2214 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002215 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002216 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002217 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2218 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002219 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002220 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002221 }
David Sodman4a36e932017-11-07 14:29:47 -08002222 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002223 }
David Sodman4a36e932017-11-07 14:29:47 -08002224 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002225
2226 {
2227 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002228 if (mTexturePool.size() < mTexturePoolSize) {
2229 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002230 const size_t offset = mTexturePool.size();
2231 mTexturePool.resize(mTexturePoolSize);
2232 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2233 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002234 } else if (mTexturePool.size() > mTexturePoolSize) {
2235 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2236 const size_t offset = mTexturePoolSize;
2237 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2238 mTexturePool.resize(mTexturePoolSize);
2239 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002240 }
2241 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002242
Kevin DuBois413287f2019-02-25 08:46:47 -08002243 if (mLumaSampling && mRegionSamplingThread) {
2244 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002245 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002246
2247 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2248 // side-effect of getTotalSize(), so we check that again here
2249 if (ATRACE_ENABLED()) {
2250 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2251 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002252}
2253
Vishnu Nair4351ad52019-02-11 14:13:02 -08002254void SurfaceFlinger::computeLayerBounds() {
2255 for (const auto& pair : mDisplays) {
2256 const auto& displayDevice = pair.second;
2257 const auto display = displayDevice->getCompositionDisplay();
2258 for (const auto& layer : mDrawingState.layersSortedByZ) {
2259 // only consider the layers on the given layer stack
2260 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002261 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002262 }
2263
2264 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2265 }
2266 }
2267}
2268
Mathias Agopiancd60f992012-08-16 16:28:27 -07002269void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002270 ATRACE_CALL();
2271 ALOGV("rebuildLayerStacks");
2272
Mathias Agopiancd60f992012-08-16 16:28:27 -07002273 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002274 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002275 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002276 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002277
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002278 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002279 const auto& displayDevice = pair.second;
2280 auto display = displayDevice->getCompositionDisplay();
2281 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002282 Region opaqueRegion;
2283 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002284 compositionengine::Output::OutputLayers layersSortedByZ;
2285 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002286 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002287 const ui::Transform& tr = displayState.transform;
2288 const Rect bounds = displayState.bounds;
2289 if (displayState.isEnabled) {
2290 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002291
Jeff Sharkey76488112017-02-27 14:15:18 -07002292 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002293 auto compositionLayer = layer->getCompositionLayer();
2294 if (compositionLayer == nullptr) {
2295 return;
2296 }
2297
Lloyd Pique32cbe282018-10-19 13:09:22 -07002298 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002299 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2300 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2301
Lloyd Pique07e33212018-12-18 16:33:37 -08002302 bool needsOutputLayer = false;
2303
Lloyd Piqueef36b002019-01-23 17:52:04 -08002304 if (display->belongsInOutput(layer->getLayerStack(),
2305 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002306 Region drawRegion(tr.transform(
2307 layer->visibleNonTransparentRegion));
2308 drawRegion.andSelf(bounds);
2309 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002310 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002311 }
Chia-I Wu83806892017-11-16 10:50:20 -08002312 }
2313
Lloyd Pique07e33212018-12-18 16:33:37 -08002314 if (needsOutputLayer) {
2315 layersSortedByZ.emplace_back(
2316 display->getOrCreateOutputLayer(displayId, compositionLayer,
2317 layerFE));
2318 deprecated_layersSortedByZ.add(layer);
2319
2320 auto& outputLayerState = layersSortedByZ.back()->editState();
2321 outputLayerState.visibleRegion =
2322 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2323 } else if (displayId) {
2324 // For layers that are being removed from a HWC display,
2325 // and that have queued frames, add them to a a list of
2326 // released layers so we can properly set a fence.
2327 bool hasExistingOutputLayer =
2328 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2329 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2330 mLayersWithQueuedFrames.cend(),
2331 layer) != mLayersWithQueuedFrames.cend();
2332
2333 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002334 layersNeedingFences.add(layer);
2335 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002336 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002337 });
2338 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002339
2340 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2341
2342 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002343 displayDevice->setLayersNeedingFences(layersNeedingFences);
2344
2345 Region undefinedRegion{bounds};
2346 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2347
2348 display->editState().undefinedRegion = undefinedRegion;
2349 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002350 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002351 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002352}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002353
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002354// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002355// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002356// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002358// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002359// The returned HDR data space is one of
2360// - Dataspace::UNKNOWN
2361// - Dataspace::BT2020_HLG
2362// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002363Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2364 Dataspace* outHdrDataSpace,
2365 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002366 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002367 *outHdrDataSpace = Dataspace::UNKNOWN;
2368
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002369 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002370 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371 case Dataspace::V0_SCRGB:
2372 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002373 case Dataspace::BT2020:
2374 case Dataspace::BT2020_ITU:
2375 case Dataspace::BT2020_LINEAR:
2376 case Dataspace::DISPLAY_BT2020:
2377 bestDataSpace = Dataspace::DISPLAY_BT2020;
2378 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002379 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002380 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002381 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002382 case Dataspace::BT2020_PQ:
2383 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002384 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002385 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002386 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002388 case Dataspace::BT2020_HLG:
2389 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002390 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002391 // When there's mixed PQ content and HLG content, we set the HDR
2392 // data space to be BT2020_PQ and convert HLG to PQ.
2393 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2394 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002395 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002396 break;
2397 default:
2398 break;
2399 }
Romain Guy54f154a2017-10-24 21:40:32 +01002400 }
2401
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002402 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002403}
2404
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002405// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2407 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002408 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2409 *outMode = ColorMode::NATIVE;
2410 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002411 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002412 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002413 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002414
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002415 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002416 bool isHdrClientComposition = false;
2417 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002418
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002419 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2420
Peiyong Lina3ea5592019-02-10 14:45:00 -08002421 switch (mForceColorMode) {
2422 case ColorMode::SRGB:
2423 bestDataSpace = Dataspace::V0_SRGB;
2424 break;
2425 case ColorMode::DISPLAY_P3:
2426 bestDataSpace = Dataspace::DISPLAY_P3;
2427 break;
2428 default:
2429 break;
2430 }
2431
Peiyong Lindfde5112018-06-05 10:58:41 -07002432 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002433 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2434 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002435 if (isHdr) {
2436 bestDataSpace = hdrDataSpace;
2437 }
2438
Chia-I Wu0d711262018-05-21 15:19:35 -07002439 RenderIntent intent;
2440 switch (mDisplayColorSetting) {
2441 case DisplayColorSetting::MANAGED:
2442 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002443 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002444 break;
2445 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002446 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002447 break;
2448 default: // vendor display color setting
2449 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2450 break;
2451 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002452
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002453 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002454}
2455
Lloyd Pique32cbe282018-10-19 13:09:22 -07002456void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2457 auto display = displayDevice->getCompositionDisplay();
2458 const auto& displayState = display->getState();
2459
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002460 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002461 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2462 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002463
David Sodmanfa9b2af2017-12-24 13:28:59 -08002464 // If nothing has changed (!dirty), don't recompose.
2465 // If something changed, but we don't currently have any visible layers,
2466 // and didn't when we last did a composition, then skip it this time.
2467 // The second rule does two things:
2468 // - When all layers are removed from a display, we'll emit one black
2469 // frame, then nothing more until we get new layers.
2470 // - When a display is created with a private layer stack, we won't
2471 // emit any black frames until a layer is added to the layer stack.
2472 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002473
Dominik Laskowski075d3172018-05-24 15:50:06 -07002474 const char flagPrefix[] = {'-', '+'};
2475 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002476 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2477 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2478 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2479 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002480
Lloyd Pique31cb2942018-10-19 17:23:03 -07002481 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002482
David Sodmanfa9b2af2017-12-24 13:28:59 -08002483 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002484 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002485 }
2486}
2487
Lloyd Pique32cbe282018-10-19 13:09:22 -07002488void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2489 auto display = displayDevice->getCompositionDisplay();
2490 const auto& displayState = display->getState();
2491
2492 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002493 return;
David Sodman2b406362017-12-15 13:33:47 -08002494 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002495
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002496 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002497 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002498 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002499}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002500
Lloyd Pique32cbe282018-10-19 13:09:22 -07002501void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002502 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002503 ALOGV("doComposition");
2504
Lloyd Pique32cbe282018-10-19 13:09:22 -07002505 auto display = displayDevice->getCompositionDisplay();
2506 const auto& displayState = display->getState();
2507
2508 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002509 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002510 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002511
David Sodmanfa9b2af2017-12-24 13:28:59 -08002512 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002513 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002514
Lloyd Pique32cbe282018-10-19 13:09:22 -07002515 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002516 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002517 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002518 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002519}
2520
David Sodmanfa9b2af2017-12-24 13:28:59 -08002521void SurfaceFlinger::postFrame()
2522{
2523 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524 const auto display = getDefaultDisplayDeviceLocked();
2525 if (display && getHwComposer().isConnected(*display->getId())) {
2526 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002527 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2528 logFrameStats();
2529 }
2530 }
2531}
2532
Lloyd Pique32cbe282018-10-19 13:09:22 -07002533void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002534 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002535 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002536
Lloyd Pique32cbe282018-10-19 13:09:22 -07002537 auto display = displayDevice->getCompositionDisplay();
2538 const auto& displayState = display->getState();
2539 const auto displayId = display->getId();
2540
Lloyd Pique32cbe282018-10-19 13:09:22 -07002541 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002542 if (displayId) {
2543 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002544 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002545 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002546 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002547 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002548 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002549
Chia-I Wu7b549592017-11-15 09:14:57 -08002550 // The layer buffer from the previous frame (if any) is released
2551 // by HWC only when the release fence from this frame (if any) is
2552 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002553 if (layer->getState().hwc) {
2554 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002555 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002556 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2557 usedClientComposition =
2558 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002559 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002560
2561 // If the layer was client composited in the previous frame, we
2562 // need to merge with the previous client target acquire fence.
2563 // Since we do not track that, always merge with the current
2564 // client target acquire fence when it is available, even though
2565 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002566 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002567 releaseFence =
2568 Fence::merge("LayerRelease", releaseFence,
2569 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002570 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002571
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002572 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002573 }
Chia-I Wu83806892017-11-16 10:50:20 -08002574
2575 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002576 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002577 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002578 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002579 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002580 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002581 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002582 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002583 }
2584 }
2585
Dominik Laskowski075d3172018-05-24 15:50:06 -07002586 if (displayId) {
2587 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002588 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002589 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590}
2591
Mathias Agopian87baae12012-07-31 12:38:26 -07002592void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002593{
Mathias Agopian841cde52012-03-01 15:44:37 -08002594 ATRACE_CALL();
2595
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002596 // here we keep a copy of the drawing state (that is the state that's
2597 // going to be overwritten by handleTransactionLocked()) outside of
2598 // mStateLock so that the side-effects of the State assignment
2599 // don't happen with mStateLock held (which can cause deadlocks).
2600 State drawingState(mDrawingState);
2601
Mathias Agopianca4d3602011-05-19 15:38:14 -07002602 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002603 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604
Mathias Agopianca4d3602011-05-19 15:38:14 -07002605 // Here we're guaranteed that some transaction flags are set
2606 // so we can call handleTransactionLocked() unconditionally.
2607 // We call getTransactionFlags(), which will also clear the flags,
2608 // with mStateLock held to guarantee that mCurrentState won't change
2609 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002610
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002611 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002612 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002613 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002614
Mathias Agopianca4d3602011-05-19 15:38:14 -07002615 mDebugInTransaction = 0;
2616 invalidateHwcGeometry();
2617 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002618}
2619
Lloyd Piqueba04e622017-12-14 17:11:26 -08002620void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2621 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002622 const std::optional<DisplayIdentificationInfo> info =
2623 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002624
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002626 continue;
2627 }
2628
Lloyd Piqueba04e622017-12-14 17:11:26 -08002629 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002630 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002631 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002632 mPhysicalDisplayTokens[info->id] = new BBinder();
2633 DisplayDeviceState state;
2634 state.displayId = info->id;
2635 state.isSecure = true; // All physical displays are currently considered secure.
2636 state.displayName = info->name;
2637 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2638 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002639 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002640 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002641 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002642
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2644 if (index >= 0) {
2645 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2646 mInterceptor->saveDisplayDeletion(state.sequenceId);
2647 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002648 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002649 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002650 }
2651
2652 processDisplayChangesLocked();
2653 }
2654
2655 mPendingHotplugEvents.clear();
2656}
2657
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002658void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002659 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2660 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002661}
2662
Lloyd Pique99d3da52018-01-22 17:48:03 -08002663sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002664 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002665 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 const sp<IGraphicBufferProducer>& producer) {
2667 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002668 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002670 creationArgs.isSecure = state.isSecure;
2671 creationArgs.displaySurface = dispSurface;
2672 creationArgs.hasWideColorGamut = false;
2673 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002674
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002675 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002676 creationArgs.isPrimary = isInternalDisplay;
2677
2678 if (useColorManagement && displayId) {
2679 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002680 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002681 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002682 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002683 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002684
Dominik Laskowski7e045462018-05-30 13:02:02 -07002685 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002686 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002687 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002688 }
tangrobin6753a022018-08-10 10:58:54 +08002689 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002690
Dominik Laskowski075d3172018-05-24 15:50:06 -07002691 if (displayId) {
2692 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002693 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002694 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002695 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002696
Lloyd Pique90c115d2018-09-18 21:39:42 -07002697 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002698 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002699 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002700
Lloyd Pique99d3da52018-01-22 17:48:03 -08002701 // Make sure that composition can never be stalled by a virtual display
2702 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002703 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002704 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002705 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2706 }
2707
Dominik Laskowski075d3172018-05-24 15:50:06 -07002708 creationArgs.displayInstallOrientation =
2709 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002710
Lloyd Pique99d3da52018-01-22 17:48:03 -08002711 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002712 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002713
Lloyd Pique90c115d2018-09-18 21:39:42 -07002714 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002715
2716 if (maxFrameBufferAcquiredBuffers >= 3) {
2717 nativeWindowSurface->preallocateBuffers();
2718 }
2719
2720 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002721 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002722 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002723 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002724 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002725 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002726 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2727 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002728 if (!state.isVirtual()) {
2729 LOG_ALWAYS_FATAL_IF(!displayId);
2730 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002731 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002732
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002733 display->setLayerStack(state.layerStack);
2734 display->setProjection(state.orientation, state.viewport, state.frame);
2735 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002736
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002737 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002738}
2739
Lloyd Pique347200f2017-12-14 17:00:15 -08002740void SurfaceFlinger::processDisplayChangesLocked() {
2741 // here we take advantage of Vector's copy-on-write semantics to
2742 // improve performance by skipping the transaction entirely when
2743 // know that the lists are identical
2744 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2745 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2746 if (!curr.isIdenticalTo(draw)) {
2747 mVisibleRegionsDirty = true;
2748 const size_t cc = curr.size();
2749 size_t dc = draw.size();
2750
2751 // find the displays that were removed
2752 // (ie: in drawing state but not in current state)
2753 // also handle displays that changed
2754 // (ie: displays that are in both lists)
2755 for (size_t i = 0; i < dc;) {
2756 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2757 if (j < 0) {
2758 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002760 // Save display ID before disconnecting.
2761 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002762 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002763
2764 if (!display->isVirtual()) {
2765 LOG_ALWAYS_FATAL_IF(!displayId);
2766 dispatchDisplayHotplugEvent(displayId->value, false);
2767 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002768 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002769
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002770 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002771 } else {
2772 // this display is in both lists. see if something changed.
2773 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002774 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002775 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2776 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2777 if (state_binder != draw_binder) {
2778 // changing the surface is like destroying and
2779 // recreating the DisplayDevice, so we just remove it
2780 // from the drawing state, so that it get re-added
2781 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002782 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002783 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002784 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002785 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002786 mDrawingState.displays.removeItemsAt(i);
2787 dc--;
2788 // at this point we must loop to the next item
2789 continue;
2790 }
2791
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002792 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002793 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002794 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002795 }
2796 if ((state.orientation != draw[i].orientation) ||
2797 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002798 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002799 }
2800 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002801 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002802 }
2803 }
2804 }
2805 ++i;
2806 }
2807
2808 // find displays that were added
2809 // (ie: in current state but not in drawing state)
2810 for (size_t i = 0; i < cc; i++) {
2811 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2812 const DisplayDeviceState& state(curr[i]);
2813
Lloyd Pique542307f2018-10-19 13:24:08 -07002814 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002815 sp<IGraphicBufferProducer> producer;
2816 sp<IGraphicBufferProducer> bqProducer;
2817 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002818 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002819
Dominik Laskowski075d3172018-05-24 15:50:06 -07002820 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002821 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002822 // Virtual displays without a surface are dormant:
2823 // they have external state (layer stack, projection,
2824 // etc.) but no internal state (i.e. a DisplayDevice).
2825 if (state.surface != nullptr) {
2826 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002827 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002828 int width = 0;
2829 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2830 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2831 int height = 0;
2832 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2833 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2834 int intFormat = 0;
2835 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2836 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002837 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002838
Dominik Laskowski075d3172018-05-24 15:50:06 -07002839 displayId =
2840 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002841 }
2842
2843 // TODO: Plumb requested format back up to consumer
2844
2845 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002846 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002847 bqProducer, bqConsumer,
2848 state.displayName);
2849
2850 dispSurface = vds;
2851 producer = vds;
2852 }
2853 } else {
2854 ALOGE_IF(state.surface != nullptr,
2855 "adding a supported display, but rendering "
2856 "surface is provided (%p), ignoring it",
2857 state.surface.get());
2858
Dominik Laskowski075d3172018-05-24 15:50:06 -07002859 displayId = state.displayId;
2860 LOG_ALWAYS_FATAL_IF(!displayId);
2861 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002862 producer = bqProducer;
2863 }
2864
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002865 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002866 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002867 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002868 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002869 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002870 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002871 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002872 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002873 }
2874 }
2875 }
2876 }
2877 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002878
2879 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002880}
2881
Mathias Agopian87baae12012-07-31 12:38:26 -07002882void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002883{
Dan Stoza7dde5992015-05-22 09:51:44 -07002884 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002885 mCurrentState.traverseInZOrder([](Layer* layer) {
2886 layer->notifyAvailableFrames();
2887 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002888
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002889 /*
2890 * Traversal of the children
2891 * (perform the transaction for each of them if needed)
2892 */
2893
Marissa Wall06255332019-03-27 13:48:27 -07002894 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002895 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002896 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002897 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002898
2899 const uint32_t flags = layer->doTransaction(0);
2900 if (flags & Layer::eVisibleRegion)
2901 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002902
2903 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002904 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002905 }
Robert Carr2047fae2016-11-28 14:09:09 -08002906 });
Marissa Wall06255332019-03-27 13:48:27 -07002907 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 }
2909
2910 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002911 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 */
2913
Mathias Agopiane57f2922012-08-09 16:29:12 -07002914 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002915 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002916 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002917 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002918
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002919 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002920 // The transform hint might have changed for some layers
2921 // (either because a display has changed, or because a layer
2922 // as changed).
2923 //
2924 // Walk through all the layers in currentLayers,
2925 // and update their transform hint.
2926 //
2927 // If a layer is visible only on a single display, then that
2928 // display is used to calculate the hint, otherwise we use the
2929 // default display.
2930 //
2931 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2932 // the hint is set before we acquire a buffer from the surface texture.
2933 //
2934 // NOTE: layer transactions have taken place already, so we use their
2935 // drawing state. However, SurfaceFlinger's own transaction has not
2936 // happened yet, so we must use the current state layer list
2937 // (soon to become the drawing state list).
2938 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002939 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002940 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002941 bool first = true;
2942 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002943 // NOTE: we rely on the fact that layers are sorted by
2944 // layerStack first (so we don't have to traverse the list
2945 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002946 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002947 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002948 currentlayerStack = layerStack;
2949 // figure out if this layerstack is mirrored
2950 // (more than one display) if so, pick the default display,
2951 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 hintDisplay = nullptr;
2953 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002954 if (display->getCompositionDisplay()
2955 ->belongsInOutput(layer->getLayerStack(),
2956 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002957 if (hintDisplay) {
2958 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002959 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002960 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002961 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002962 }
2963 }
2964 }
2965 }
Chet Haase91d25932013-04-11 15:24:55 -07002966
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002967 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002968 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2969 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002970
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002971 // could be null when this layer is using a layerStack
2972 // that is not visible on any display. Also can occur at
2973 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002974 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002975 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002976
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002977 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002978 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002979 if (hintDisplay) {
2980 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002981 }
Robert Carr2047fae2016-11-28 14:09:09 -08002982
2983 first = false;
2984 });
Mathias Agopian84300952012-11-21 16:02:13 -08002985 }
2986
2987
Mathias Agopian3559b072012-08-15 13:46:03 -07002988 /*
2989 * Perform our own transaction if needed
2990 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002991
2992 if (mLayersAdded) {
2993 mLayersAdded = false;
2994 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002995 mVisibleRegionsDirty = true;
2996 }
2997
2998 // some layers might have been removed, so
2999 // we need to update the regions they're exposing.
3000 if (mLayersRemoved) {
3001 mLayersRemoved = false;
3002 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08003003 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003004 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07003005 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07003006 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08003007 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07003008 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07003009 }
Robert Carr2047fae2016-11-28 14:09:09 -08003010 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003011 }
3012
Vishnu Nairec0ab382019-02-13 15:32:56 -08003013 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003014 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07003015}
3016
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003017void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07003018 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003019 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08003020 return;
3021 }
3022
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003023 if (mVisibleRegionsDirty || mInputInfoChanged) {
3024 mInputInfoChanged = false;
3025 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08003026 } else if (mInputWindowCommands.syncInputWindows) {
3027 // If the caller requested to sync input windows, but there are no
3028 // changes to input windows, notify immediately.
3029 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003030 }
3031
Arthur Hung5845eaf2019-09-05 16:38:18 +08003032 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003033}
3034
3035void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003036 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07003037
3038 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3039 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003040 // When calculating the screen bounds we ignore the transparent region since it may
3041 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003042 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003043 }
3044 });
chaviw291d88a2019-02-14 10:33:58 -08003045
3046 mInputFlinger->setInputWindows(inputHandles,
3047 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3048 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003049}
3050
Vishnu Nairec0ab382019-02-13 15:32:56 -08003051void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07003052 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08003053 mPendingInputWindowCommands.clear();
3054}
3055
Riley Andrews03414a12014-07-01 14:22:59 -07003056void SurfaceFlinger::updateCursorAsync()
3057{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003058 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003059 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003060 continue;
3061 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003063 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3064 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003065 }
3066 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003067}
3068
chaviw61626f22018-11-15 16:26:27 -08003069void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3070 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003071 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003072 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003073 }
3074 layer->releasePendingBuffer(systemTime());
3075}
3076
Mathias Agopian4fec8732012-06-29 14:12:52 -07003077void SurfaceFlinger::commitTransaction()
3078{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003079 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003080 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003081 for (const auto& l : mLayersPendingRemoval) {
3082 recordBufferingStats(l->getName().string(),
3083 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003084
Lloyd Pique07e33212018-12-18 16:33:37 -08003085 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003086 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003087 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003088 }
chaviw74d90ad2019-04-26 14:45:26 -07003089
3090 // If the layer has been removed and has no parent, then it will not be reachable
3091 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3092 // ensure we can copy its current to drawing state.
3093 if (!l->getParent()) {
3094 mOffscreenLayers.emplace(l.get());
3095 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003096 }
3097 mLayersPendingRemoval.clear();
3098 }
3099
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003100 // If this transaction is part of a window animation then the next frame
3101 // we composite should be considered an animation as well.
3102 mAnimCompositionPending = mAnimTransactionPending;
3103
Nataniel Borges2b796da2019-02-15 13:32:18 -08003104 withTracingLock([&]() {
3105 mDrawingState = mCurrentState;
3106 // clear the "changed" flags in current state
3107 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003108
chaviw74d90ad2019-04-26 14:45:26 -07003109 mDrawingState.traverseInZOrder([&](Layer* layer) {
3110 layer->commitChildList();
3111
3112 // If the layer can be reached when traversing mDrawingState, then the layer is no
3113 // longer offscreen. Remove the layer from the offscreenLayer set.
3114 if (mOffscreenLayers.count(layer)) {
3115 mOffscreenLayers.erase(layer);
3116 }
3117 });
3118
3119 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003120 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003121
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003122 mTransactionPending = false;
3123 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003124 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003125}
3126
Nataniel Borges2b796da2019-02-15 13:32:18 -08003127void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3128 if (mTracingEnabledChanged) {
3129 mTracingEnabled = mTracing.isEnabled();
3130 mTracingEnabledChanged = false;
3131 }
3132
3133 // Synchronize with Tracing thread
3134 std::unique_lock<std::mutex> lock;
3135 if (mTracingEnabled) {
3136 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3137 }
3138
3139 lockedOperation();
3140
3141 // Synchronize with Tracing thread
3142 if (mTracingEnabled) {
3143 lock.unlock();
3144 }
3145}
3146
chaviw74d90ad2019-04-26 14:45:26 -07003147void SurfaceFlinger::commitOffscreenLayers() {
3148 for (Layer* offscreenLayer : mOffscreenLayers) {
3149 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3150 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3151 if (!trFlags) return;
3152
3153 layer->doTransaction(0);
3154 layer->commitChildList();
3155 });
3156 }
3157}
3158
Lloyd Pique32cbe282018-10-19 13:09:22 -07003159void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003160 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003161 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003162 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003163
Lloyd Pique32cbe282018-10-19 13:09:22 -07003164 auto display = displayDevice->getCompositionDisplay();
3165
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003166 Region aboveOpaqueLayers;
3167 Region aboveCoveredLayers;
3168 Region dirty;
3169
Mathias Agopian87baae12012-07-31 12:38:26 -07003170 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003171
Robert Carr2047fae2016-11-28 14:09:09 -08003172 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003173 // start with the whole surface at its current location
3174 const Layer::State& s(layer->getDrawingState());
3175
Jesse Hall01e29052013-02-19 16:13:35 -08003176 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003177 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003178 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003179 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003180
Mathias Agopianab028732010-03-16 16:41:46 -07003181 /*
3182 * opaqueRegion: area of a surface that is fully opaque.
3183 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003185
3186 /*
3187 * visibleRegion: area of a surface that is visible on screen
3188 * and not fully transparent. This is essentially the layer's
3189 * footprint minus the opaque regions above it.
3190 * Areas covered by a translucent surface are considered visible.
3191 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003192 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003193
3194 /*
3195 * coveredRegion: area of a surface that is covered by all
3196 * visible regions above it (which includes the translucent areas).
3197 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003199
Jesse Halla8026d22012-09-25 13:25:04 -07003200 /*
3201 * transparentRegion: area of a surface that is hinted to be completely
3202 * transparent. This is only used to tell when the layer has no visible
3203 * non-transparent regions and can be removed from the layer list. It
3204 * does not affect the visibleRegion of this layer or any layers
3205 * beneath it. The hint may not be correct if apps don't respect the
3206 * SurfaceView restrictions (which, sadly, some don't).
3207 */
3208 Region transparentRegion;
3209
Mathias Agopianab028732010-03-16 16:41:46 -07003210
3211 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003212 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003213 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003214 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003215
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003216 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003217 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003218 if (!visibleRegion.isEmpty()) {
3219 // Remove the transparent area from the visible region
3220 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003221 if (tr.preserveRects()) {
3222 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003223 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003224 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003225 // transformation too complex, can't do the
3226 // transparent region optimization.
3227 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003228 }
Mathias Agopianab028732010-03-16 16:41:46 -07003229 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230
Mathias Agopianab028732010-03-16 16:41:46 -07003231 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003232 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003233 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003234 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003235 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003236 // the opaque region is the layer's footprint
3237 opaqueRegion = visibleRegion;
3238 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 }
3240 }
3241
Robert Carre5f4f692018-01-12 13:12:28 -08003242 if (visibleRegion.isEmpty()) {
3243 layer->clearVisibilityRegions();
3244 return;
3245 }
3246
Mathias Agopianab028732010-03-16 16:41:46 -07003247 // Clip the covered region to the visible region
3248 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3249
3250 // Update aboveCoveredLayers for next (lower) layer
3251 aboveCoveredLayers.orSelf(visibleRegion);
3252
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003253 // subtract the opaque region covered by the layers above us
3254 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003255
3256 // compute this layer's dirty region
3257 if (layer->contentDirty) {
3258 // we need to invalidate the whole region
3259 dirty = visibleRegion;
3260 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003261 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262 layer->contentDirty = false;
3263 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003264 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003265 * the exposed region consists of two components:
3266 * 1) what's VISIBLE now and was COVERED before
3267 * 2) what's EXPOSED now less what was EXPOSED before
3268 *
3269 * note that (1) is conservative, we start with the whole
3270 * visible region but only keep what used to be covered by
3271 * something -- which mean it may have been exposed.
3272 *
3273 * (2) handles areas that were not covered by anything but got
3274 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003275 */
Mathias Agopianab028732010-03-16 16:41:46 -07003276 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003277 const Region oldVisibleRegion = layer->visibleRegion;
3278 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003279 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3280 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003281 }
3282 dirty.subtractSelf(aboveOpaqueLayers);
3283
3284 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003285 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286
Mathias Agopianab028732010-03-16 16:41:46 -07003287 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003288 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003289
Jesse Halla8026d22012-09-25 13:25:04 -07003290 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003291 layer->setVisibleRegion(visibleRegion);
3292 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003293 layer->setVisibleNonTransparentRegion(
3294 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003295 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003296
Mathias Agopian87baae12012-07-31 12:38:26 -07003297 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298}
3299
Chia-I Wuab0c3192017-08-01 11:29:00 -07003300void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003301 for (const auto& [token, displayDevice] : mDisplays) {
3302 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003303 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003304 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003305 }
3306 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003307}
3308
Dan Stoza6b9454d2014-11-07 16:00:59 -08003309bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003310{
Ady Abraham09bd3922019-04-08 10:44:56 -07003311 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003312 ALOGV("handlePageFlip");
3313
Brian Andersond6927fb2016-07-23 23:37:30 -07003314 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315
Mathias Agopian4fec8732012-06-29 14:12:52 -07003316 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003317 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003318 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003319
3320 // Store the set of layers that need updates. This set must not change as
3321 // buffers are being latched, as this could result in a deadlock.
3322 // Example: Two producers share the same command stream and:
3323 // 1.) Layer 0 is latched
3324 // 2.) Layer 0 gets a new frame
3325 // 2.) Layer 1 gets a new frame
3326 // 3.) Layer 1 is latched.
3327 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3328 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003329 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003330 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003331 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003332 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003333 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003334 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003335 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003336 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003337 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003338 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003339 } else {
3340 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003341 }
Robert Carr2047fae2016-11-28 14:09:09 -08003342 });
3343
Lloyd Piquef2c79392018-12-20 16:23:33 -08003344 if (!mLayersWithQueuedFrames.empty()) {
3345 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3346 // writes to Layer current state. See also b/119481871
3347 Mutex::Autolock lock(mStateLock);
3348
3349 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003350 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003351 mLayersPendingRefresh.push_back(layer);
3352 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003353 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003354 if (layer->isBufferLatched()) {
3355 newDataLatched = true;
3356 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003357 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003358 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003359
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003360 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003361
3362 // If we will need to wake up at some time in the future to deal with a
3363 // queued frame that shouldn't be displayed during this vsync period, wake
3364 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003365 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003366 signalLayerUpdate();
3367 }
3368
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003369 // enter boot animation on first buffer latch
3370 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3371 ALOGI("Enter boot animation");
3372 mBootStage = BootStage::BOOTANIMATION;
3373 }
3374
Dan Stoza6b9454d2014-11-07 16:00:59 -08003375 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003376 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003377}
3378
Mathias Agopianad456f92011-01-13 17:53:01 -08003379void SurfaceFlinger::invalidateHwcGeometry()
3380{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003381 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003382}
3383
Lloyd Pique32cbe282018-10-19 13:09:22 -07003384void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003385 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003386 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003387 // We only need to actually compose the display if:
3388 // 1) It is being handled by hardware composer, which may need this to
3389 // keep its virtual display state machine in sync, or
3390 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003391 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003392 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003393 return;
3394 }
3395
Dan Stoza9e56aa02015-11-02 13:00:03 -08003396 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003397 base::unique_fd readyFence;
3398 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003399
3400 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003401 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003402}
3403
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003404bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3405 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003406 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003407 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003408
Lloyd Pique32cbe282018-10-19 13:09:22 -07003409 auto display = displayDevice->getCompositionDisplay();
3410 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003411 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003412 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003413 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003414
3415 const Region bounds(displayState.bounds);
3416 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003417 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Baldev Sahu0560e0e2018-09-27 15:02:33 +05303418 const bool hasFlipClientTargetRequest = getHwComposer().hasFlipClientTargetRequest(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003419 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003420
Chia-I Wu8e50e692018-05-04 10:12:37 -07003421 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003422
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003423 renderengine::DisplaySettings clientCompositionDisplay;
3424 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3425 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003426 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003427
Dan Stoza9e56aa02015-11-02 13:00:03 -08003428 if (hasClientComposition) {
3429 ALOGV("hasClientComposition");
3430
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003431 if (displayDevice->isPrimary() && supportProtectedContent) {
3432 bool needsProtected = false;
3433 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3434 // If the layer is a protected layer, mark protected context is needed.
3435 if (layer->isProtected()) {
3436 needsProtected = true;
3437 break;
3438 }
3439 }
Peiyong Lin52010312019-05-02 14:22:16 -07003440 if (needsProtected != renderEngine.isProtected()) {
3441 renderEngine.useProtectedContext(needsProtected);
3442 }
3443 if (needsProtected != display->getRenderSurface()->isProtected() &&
3444 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003445 display->getRenderSurface()->setProtected(needsProtected);
3446 }
3447 }
3448
Alec Mouri6338c9d2019-02-07 16:57:51 -08003449 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003450
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003451 if (buf == nullptr) {
3452 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3453 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003454 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003455 return false;
3456 }
3457
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003458 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3459 clientCompositionDisplay.clip = displayState.scissor;
3460 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003461 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003462 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003463
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003464 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003465 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003466 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003467 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003468 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003469 clientCompositionDisplay.outputDataspace = outputDataspace;
3470 clientCompositionDisplay.maxLuminance =
3471 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003472
Lloyd Pique441d5042018-10-18 16:49:51 -07003473 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003474 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003475 getHwComposer()
3476 .hasDisplayCapability(displayId,
3477 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003478
Peiyong Lind3788632018-09-18 16:01:31 -07003479 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003480 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3481 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003482 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003483 }
Baldev Sahu0560e0e2018-09-27 15:02:33 +05303484 } else if (hasFlipClientTargetRequest) {
3485 buf = display->getRenderSurface()->dequeueBuffer(&fd);
3486
3487 if (buf == nullptr) {
3488 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3489 "client composition for this frame",
3490 displayDevice->getDisplayName().c_str());
3491 return false;
3492 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003493 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003494
Mathias Agopian85d751c2012-08-29 16:59:24 -07003495 /*
3496 * and then, render the layers targeted at the framebuffer
3497 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003498
Dan Stoza9e56aa02015-11-02 13:00:03 -08003499 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003500 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003501 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003502 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003503 const Region viewportRegion(displayState.viewport);
3504 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003505 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003506 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003507 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003508 switch (layer->getCompositionType(displayDevice)) {
3509 case Hwc2::IComposerClient::Composition::CURSOR:
3510 case Hwc2::IComposerClient::Composition::DEVICE:
3511 case Hwc2::IComposerClient::Composition::SIDEBAND:
3512 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003513 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003514 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003515 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003516 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003517 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003518 // never clear the very first layer since we're
3519 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003520 renderengine::LayerSettings layerSettings;
3521 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003522 bool prepared =
3523 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3524 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003525
3526 if (prepared) {
3527 layerSettings.source.buffer.buffer = nullptr;
3528 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3529 layerSettings.alpha = half(0.0);
3530 layerSettings.disableBlending = true;
3531 clientCompositionLayers.push_back(layerSettings);
3532 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003533 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003534 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003535 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003536 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003537 renderengine::LayerSettings layerSettings;
3538 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003539 layer->prepareClientLayer(renderArea, clip, clearRegion,
3540 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003541 if (prepared) {
3542 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003543 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003544 break;
3545 }
3546 default:
3547 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003548 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003549 } else {
3550 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003551 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003552 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003553 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003554
Alec Mouri820c7402019-01-23 13:02:39 -08003555 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003556 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003557 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003558
3559 // We boost GPU frequency here because there will be color spaces conversion
3560 // and it's expensive. We boost the GPU frequency so that GPU composition can
3561 // finish in time. We must reset GPU frequency afterwards, because high frequency
3562 // consumes extra battery.
3563 const bool expensiveRenderingExpected =
3564 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3565 if (expensiveRenderingExpected && displayId) {
3566 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3567 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003568 if (!debugRegion.isEmpty()) {
3569 Region::const_iterator it = debugRegion.begin();
3570 Region::const_iterator end = debugRegion.end();
3571 while (it != end) {
3572 const Rect& rect = *it++;
3573 renderengine::LayerSettings layerSettings;
3574 layerSettings.source.buffer.buffer = nullptr;
3575 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3576 layerSettings.geometry.boundaries = rect.toFloatRect();
3577 layerSettings.alpha = half(1.0);
3578 clientCompositionLayers.push_back(layerSettings);
3579 }
3580 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003581 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003582 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3583 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003584 } else if (displayId) {
3585 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003586 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003587 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588}
3589
Chia-I Wu28e3a252018-09-07 12:05:02 -07003590void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003591 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003592 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003593}
3594
Robert Carrc0df3122019-04-11 13:18:21 -07003595status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3596 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3597 const sp<IBinder>& parentHandle,
3598 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003599 // add this layer to the current state list
3600 {
3601 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003602 sp<Layer> parent;
3603 if (parentHandle != nullptr) {
3604 parent = fromHandle(parentHandle);
3605 if (parent == nullptr) {
3606 return NAME_NOT_FOUND;
3607 }
3608 } else {
3609 parent = parentLayer;
3610 }
3611
Robert Carr1f0a16a2016-10-24 16:27:39 -07003612 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003613 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3614 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003615 return NO_MEMORY;
3616 }
Robert Carrc0df3122019-04-11 13:18:21 -07003617
3618 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3619
Robert Carrb89ea9d2018-12-10 13:01:14 -08003620 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003621 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003622 } else if (parent == nullptr) {
3623 lbc->onRemovedFromCurrentState();
3624 } else if (parent->isRemovedFromCurrentState()) {
3625 parent->addChild(lbc);
3626 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003627 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003628 parent->addChild(lbc);
3629 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003630
Yiwei Zhang243b3782018-05-15 17:40:04 -07003631 if (gbc != nullptr) {
3632 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3633 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3634 mMaxGraphicBufferProducerListSize,
3635 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3636 mGraphicBufferProducerList.size(),
3637 mMaxGraphicBufferProducerListSize, mNumLayers);
3638 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003639 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003640 }
3641
Mathias Agopian96f08192010-06-02 23:28:45 -07003642 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003643 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003644
Dan Stoza7d89d062015-04-30 13:29:25 -07003645 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003646}
3647
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003648uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003649 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003650}
3651
Mathias Agopian3f844832013-08-07 21:24:32 -07003652uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003653 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003654}
3655
Mathias Agopian3f844832013-08-07 21:24:32 -07003656uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003657 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003658}
3659
3660uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003661 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003662 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003663 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003664 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003665 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003666 }
3667 return old;
3668}
3669
Marissa Wall713b63f2018-10-17 15:42:43 -07003670bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003671 // to prevent onHandleDestroyed from being called while the lock is held,
3672 // we must keep a copy of the transactions (specifically the composer
3673 // states) around outside the scope of the lock
3674 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003675 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003676 {
3677 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003678
Valerie Haufce31b82019-04-30 16:41:14 -07003679 auto it = mTransactionQueues.begin();
3680 while (it != mTransactionQueues.end()) {
3681 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003682
Valerie Haufce31b82019-04-30 16:41:14 -07003683 while (!transactionQueue.empty()) {
3684 const auto& transaction = transactionQueue.front();
3685 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3686 transaction.states)) {
3687 setTransactionFlags(eTransactionFlushNeeded);
3688 break;
3689 }
3690 transactions.push_back(transaction);
3691 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3692 mPendingInputWindowCommands, transaction.desiredPresentTime,
3693 transaction.buffer, transaction.callback,
3694 transaction.postTime, transaction.privileged,
3695 /*isMainThread*/ true);
3696 transactionQueue.pop();
3697 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003698 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003699
Valerie Haufce31b82019-04-30 16:41:14 -07003700 if (transactionQueue.empty()) {
3701 it = mTransactionQueues.erase(it);
3702 mTransactionCV.broadcast();
3703 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003704 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003705 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003706 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003707 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003708 return flushedATransaction;
3709}
3710
3711bool SurfaceFlinger::transactionFlushNeeded() {
3712 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003713}
3714
chaviwca27f252018-02-06 16:46:39 -08003715bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3716 for (const ComposerState& state : states) {
3717 // Here we need to check that the interface we're given is indeed
3718 // one of our own. A malicious client could give us a nullptr
3719 // IInterface, or one of its own or even one of our own but a
3720 // different type. All these situations would cause us to crash.
3721 if (state.client == nullptr) {
3722 return true;
3723 }
3724
3725 sp<IBinder> binder = IInterface::asBinder(state.client);
3726 if (binder == nullptr) {
3727 return true;
3728 }
3729
3730 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3731 return true;
3732 }
3733 }
3734 return false;
3735}
3736
Marissa Wall17b4e452018-12-26 16:32:34 -08003737bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3738 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003739 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003740 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3741 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3742 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3743 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3744 return false;
3745 }
3746
Marissa Wall713b63f2018-10-17 15:42:43 -07003747 for (const ComposerState& state : states) {
3748 const layer_state_t& s = state.state;
3749 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3750 continue;
3751 }
3752 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003753 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003754 }
3755 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003756 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003757}
3758
3759void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3760 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003761 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003762 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003763 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003764 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003765 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003766 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003767
Valerie Haubc6ddb12019-03-08 11:10:15 -08003768 const int64_t postTime = systemTime();
3769
Robert Carr14167e02019-02-13 13:50:55 -08003770 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3771
Mathias Agopian698c0872011-06-28 19:09:31 -07003772 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003773
chaviwca27f252018-02-06 16:46:39 -08003774 if (containsAnyInvalidClientState(states)) {
3775 return;
3776 }
3777
Marissa Wall713b63f2018-10-17 15:42:43 -07003778 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003779 auto itr = mTransactionQueues.find(applyToken);
3780 // if this is an animation frame, wait until prior animation frame has
3781 // been applied by SF
3782 if (flags & eAnimation) {
3783 while (itr != mTransactionQueues.end()) {
3784 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3785 if (CC_UNLIKELY(err != NO_ERROR)) {
3786 ALOGW_IF(err == TIMED_OUT,
3787 "setTransactionState timed out "
3788 "waiting for animation frame to apply");
3789 break;
3790 }
3791 itr = mTransactionQueues.find(applyToken);
3792 }
3793 }
3794 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003795 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003796 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003797 uncacheBuffer, listenerCallbacks, postTime,
3798 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003799 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003800 return;
3801 }
3802
Valerie Haubc6ddb12019-03-08 11:10:15 -08003803 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003804 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003805}
3806
3807void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003808 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003809 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003810 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003811 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003812 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003813 const int64_t postTime, bool privileged,
3814 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003815 uint32_t transactionFlags = 0;
3816
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003817 if (flags & eAnimation) {
3818 // For window updates that are part of an animation we must wait for
3819 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003820 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003821 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003822 if (CC_UNLIKELY(err != NO_ERROR)) {
3823 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003824 // caller after a few seconds.
3825 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3826 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003827 mAnimTransactionPending = false;
3828 break;
3829 }
3830 }
3831 }
3832
chaviwca27f252018-02-06 16:46:39 -08003833 for (const DisplayState& display : displays) {
3834 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003835 }
3836
Marissa Walld600d572019-03-26 15:38:50 -07003837 // In case the client has sent a Transaction that should receive callbacks but without any
3838 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3839 // to the callback thread so it can send an empty callback
3840 if (!listenerCallbacks.empty()) {
3841 mTransactionCompletedThread.run();
3842 }
3843 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3844 mTransactionCompletedThread.addCallback(listener, callbackIds);
3845 }
3846
Marissa Walle2ffb422018-10-12 11:33:52 -07003847 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003848 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003849 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3850 postTime, privileged);
3851 }
3852
Marissa Walle2ffb422018-10-12 11:33:52 -07003853 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003854 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003855 mTransactionCompletedThread.sendCallbacks();
3856 }
3857 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003858
chaviw273171b2018-12-26 11:46:30 -08003859 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3860
Marissa Wall947d34e2019-03-29 14:03:53 -07003861 if (uncacheBuffer.isValid()) {
3862 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003863 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003864 }
3865
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003866 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3867 // anyway. This can be used as a flush mechanism for previous async transactions.
3868 // Empty animation transaction can be used to simulate back-pressure, so also force a
3869 // transaction for empty animation transactions.
3870 if (transactionFlags == 0 &&
3871 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003872 transactionFlags = eTransactionNeeded;
3873 }
3874
Marissa Wall06255332019-03-27 13:48:27 -07003875 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3876 // so we don't have to wake up again next frame to preform an uneeded traversal.
3877 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3878 transactionFlags = transactionFlags & (~eTraversalNeeded);
3879 mTraversalNeededMainThread = true;
3880 }
3881
Mathias Agopian386aa982011-11-07 21:58:03 -08003882 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003883 if (mInterceptor->isEnabled()) {
3884 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003885 }
Irvel468051e2016-06-13 16:44:44 -07003886
Mathias Agopian386aa982011-11-07 21:58:03 -08003887 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003888 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3889 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003890 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003891
3892 // if this is a synchronous transaction, wait for it to take effect
3893 // before returning.
3894 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003895 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003896 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003897 if (flags & eAnimation) {
3898 mAnimTransactionPending = true;
3899 }
chaviw4fe36852019-04-15 16:25:49 -07003900 if (mPendingInputWindowCommands.syncInputWindows) {
3901 mPendingSyncInputWindows = true;
3902 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003903
3904 // applyTransactionState can be called by either the main SF thread or by
3905 // another process through setTransactionState. While a given process may wish
3906 // to wait on synchronous transactions, the main SF thread should never
3907 // be blocked. Therefore, we only wait if isMainThread is false.
3908 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003909 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3910 if (CC_UNLIKELY(err != NO_ERROR)) {
3911 // just in case something goes wrong in SF, return to the
3912 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003913 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3914 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003915 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003916 break;
3917 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003918 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003919 }
3920}
3921
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003922uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3923 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3924 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003925
Mathias Agopiane57f2922012-08-09 16:29:12 -07003926 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003927 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3928
3929 const uint32_t what = s.what;
3930 if (what & DisplayState::eSurfaceChanged) {
3931 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3932 state.surface = s.surface;
3933 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003934 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003935 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003936 if (what & DisplayState::eLayerStackChanged) {
3937 if (state.layerStack != s.layerStack) {
3938 state.layerStack = s.layerStack;
3939 flags |= eDisplayTransactionNeeded;
3940 }
3941 }
3942 if (what & DisplayState::eDisplayProjectionChanged) {
3943 if (state.orientation != s.orientation) {
3944 state.orientation = s.orientation;
3945 flags |= eDisplayTransactionNeeded;
3946 }
3947 if (state.frame != s.frame) {
3948 state.frame = s.frame;
3949 flags |= eDisplayTransactionNeeded;
3950 }
3951 if (state.viewport != s.viewport) {
3952 state.viewport = s.viewport;
3953 flags |= eDisplayTransactionNeeded;
3954 }
3955 }
3956 if (what & DisplayState::eDisplaySizeChanged) {
3957 if (state.width != s.width) {
3958 state.width = s.width;
3959 flags |= eDisplayTransactionNeeded;
3960 }
3961 if (state.height != s.height) {
3962 state.height = s.height;
3963 flags |= eDisplayTransactionNeeded;
3964 }
3965 }
3966
Mathias Agopiane57f2922012-08-09 16:29:12 -07003967 return flags;
3968}
3969
Robert Carr14167e02019-02-13 13:50:55 -08003970bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003971 IPCThreadState* ipc = IPCThreadState::self();
3972 const int pid = ipc->getCallingPid();
3973 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003974 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003975 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003976 return false;
3977 }
3978 return true;
3979}
3980
Marissa Wall3dad52d2019-03-22 14:03:19 -07003981uint32_t SurfaceFlinger::setClientStateLocked(
3982 const ComposerState& composerState, int64_t desiredPresentTime,
3983 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3984 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003985 const layer_state_t& s = composerState.state;
3986 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3987
Mathias Agopian13127d82013-03-05 17:47:11 -08003988 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003989 if (layer == nullptr) {
3990 return 0;
3991 }
3992
chaviw8b3871a2017-11-01 17:41:01 -07003993 uint32_t flags = 0;
3994
Garfield Tan8a3083e2018-12-03 13:21:07 -08003995 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003996 bool geometryAppliesWithResize =
3997 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003998
3999 // If we are deferring transaction, make sure to push the pending state, as otherwise the
4000 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07004001 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02004002 layer->pushPendingState();
4003 }
4004
chaviw8b3871a2017-11-01 17:41:01 -07004005 if (what & layer_state_t::ePositionChanged) {
4006 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
4007 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07004008 }
chaviw8b3871a2017-11-01 17:41:01 -07004009 }
4010 if (what & layer_state_t::eLayerChanged) {
4011 // NOTE: index needs to be calculated before we update the state
4012 const auto& p = layer->getParent();
4013 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07004014 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07004015 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07004016 mCurrentState.layersSortedByZ.removeAt(idx);
4017 mCurrentState.layersSortedByZ.add(layer);
4018 // we need traversal (state changed)
4019 // AND transaction (list changed)
4020 flags |= eTransactionNeeded|eTraversalNeeded;
4021 }
chaviw8b3871a2017-11-01 17:41:01 -07004022 } else {
4023 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004024 flags |= eTransactionNeeded|eTraversalNeeded;
4025 }
4026 }
chaviw8b3871a2017-11-01 17:41:01 -07004027 }
4028 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004029 // NOTE: index needs to be calculated before we update the state
4030 const auto& p = layer->getParent();
4031 if (p == nullptr) {
4032 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4033 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4034 mCurrentState.layersSortedByZ.removeAt(idx);
4035 mCurrentState.layersSortedByZ.add(layer);
4036 // we need traversal (state changed)
4037 // AND transaction (list changed)
4038 flags |= eTransactionNeeded|eTraversalNeeded;
4039 }
4040 } else {
4041 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4042 flags |= eTransactionNeeded|eTraversalNeeded;
4043 }
chaviw8b3871a2017-11-01 17:41:01 -07004044 }
4045 }
4046 if (what & layer_state_t::eSizeChanged) {
4047 if (layer->setSize(s.w, s.h)) {
4048 flags |= eTraversalNeeded;
4049 }
4050 }
4051 if (what & layer_state_t::eAlphaChanged) {
4052 if (layer->setAlpha(s.alpha))
4053 flags |= eTraversalNeeded;
4054 }
4055 if (what & layer_state_t::eColorChanged) {
4056 if (layer->setColor(s.color))
4057 flags |= eTraversalNeeded;
4058 }
Peiyong Lind3788632018-09-18 16:01:31 -07004059 if (what & layer_state_t::eColorTransformChanged) {
4060 if (layer->setColorTransform(s.colorTransform)) {
4061 flags |= eTraversalNeeded;
4062 }
4063 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004064 if (what & layer_state_t::eBackgroundColorChanged) {
4065 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4066 flags |= eTraversalNeeded;
4067 }
4068 }
chaviw8b3871a2017-11-01 17:41:01 -07004069 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004070 // TODO: b/109894387
4071 //
4072 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4073 // rotation. To see the problem observe that if we have a square parent, and a child
4074 // of the same size, then we rotate the child 45 degrees around it's center, the child
4075 // must now be cropped to a non rectangular 8 sided region.
4076 //
4077 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4078 // private API, and the WindowManager only uses rotation in one case, which is on a top
4079 // level layer in which cropping is not an issue.
4080 //
4081 // However given that abuse of rotation matrices could lead to surfaces extending outside
4082 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4083 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4084 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004085 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004086 flags |= eTraversalNeeded;
4087 }
4088 if (what & layer_state_t::eTransparentRegionChanged) {
4089 if (layer->setTransparentRegionHint(s.transparentRegion))
4090 flags |= eTraversalNeeded;
4091 }
4092 if (what & layer_state_t::eFlagsChanged) {
4093 if (layer->setFlags(s.flags, s.mask))
4094 flags |= eTraversalNeeded;
4095 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004096 if (what & layer_state_t::eCropChanged_legacy) {
4097 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004098 flags |= eTraversalNeeded;
4099 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004100 if (what & layer_state_t::eCornerRadiusChanged) {
4101 if (layer->setCornerRadius(s.cornerRadius))
4102 flags |= eTraversalNeeded;
4103 }
chaviw8b3871a2017-11-01 17:41:01 -07004104 if (what & layer_state_t::eLayerStackChanged) {
4105 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4106 // We only allow setting layer stacks for top level layers,
4107 // everything else inherits layer stack from its parent.
4108 if (layer->hasParent()) {
4109 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4110 layer->getName().string());
4111 } else if (idx < 0) {
4112 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4113 "that also does not appear in the top level layer list. Something"
4114 " has gone wrong.", layer->getName().string());
4115 } else if (layer->setLayerStack(s.layerStack)) {
4116 mCurrentState.layersSortedByZ.removeAt(idx);
4117 mCurrentState.layersSortedByZ.add(layer);
4118 // we need traversal (state changed)
4119 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004120 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004121 }
4122 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004123 if (what & layer_state_t::eDeferTransaction_legacy) {
4124 if (s.barrierHandle_legacy != nullptr) {
4125 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4126 } else if (s.barrierGbp_legacy != nullptr) {
4127 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004128 if (authenticateSurfaceTextureLocked(gbp)) {
4129 const auto& otherLayer =
4130 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004131 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004132 } else {
4133 ALOGE("Attempt to defer transaction to to an"
4134 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004135 }
4136 }
chaviw8b3871a2017-11-01 17:41:01 -07004137 // We don't trigger a traversal here because if no other state is
4138 // changed, we don't want this to cause any more work
4139 }
4140 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004141 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004142 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004143 if (!hadParent) {
4144 mCurrentState.layersSortedByZ.remove(layer);
4145 }
chaviw8b3871a2017-11-01 17:41:01 -07004146 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004147 }
chaviw8b3871a2017-11-01 17:41:01 -07004148 }
4149 if (what & layer_state_t::eReparentChildren) {
4150 if (layer->reparentChildren(s.reparentHandle)) {
4151 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004152 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004153 }
chaviw8b3871a2017-11-01 17:41:01 -07004154 if (what & layer_state_t::eDetachChildren) {
4155 layer->detachChildren();
4156 }
4157 if (what & layer_state_t::eOverrideScalingModeChanged) {
4158 layer->setOverrideScalingMode(s.overrideScalingMode);
4159 // We don't trigger a traversal here because if no other state is
4160 // changed, we don't want this to cause any more work
4161 }
Marissa Wall61c58622018-07-18 10:12:20 -07004162 if (what & layer_state_t::eTransformChanged) {
4163 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4164 }
4165 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4166 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4167 flags |= eTraversalNeeded;
4168 }
4169 if (what & layer_state_t::eCropChanged) {
4170 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4171 }
Marissa Wall861616d2018-10-22 12:52:23 -07004172 if (what & layer_state_t::eFrameChanged) {
4173 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4174 }
Marissa Wall61c58622018-07-18 10:12:20 -07004175 if (what & layer_state_t::eAcquireFenceChanged) {
4176 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4177 }
4178 if (what & layer_state_t::eDataspaceChanged) {
4179 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4180 }
4181 if (what & layer_state_t::eHdrMetadataChanged) {
4182 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4183 }
4184 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4185 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4186 }
4187 if (what & layer_state_t::eApiChanged) {
4188 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4189 }
4190 if (what & layer_state_t::eSidebandStreamChanged) {
4191 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4192 }
Robert Carr720e5062018-07-30 17:45:14 -07004193 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004194 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004195 layer->setInputInfo(s.inputInfo);
4196 flags |= eTraversalNeeded;
4197 } else {
4198 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4199 }
Robert Carr720e5062018-07-30 17:45:14 -07004200 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004201 if (what & layer_state_t::eMetadataChanged) {
4202 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4203 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004204 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4205 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4206 flags |= eTraversalNeeded;
4207 }
4208 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004209 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004210 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004211 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004212 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4213 }
4214 }
Marissa Wall78b72202019-03-15 14:58:34 -07004215 bool bufferChanged = what & layer_state_t::eBufferChanged;
4216 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4217 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004218 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07004219 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004220 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
4221 if (success) {
4222 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
4223 success = ClientCache::getInstance()
4224 .registerErasedRecipient(s.cachedBuffer,
4225 wp<ClientCache::ErasedRecipient>(this));
4226 if (!success) {
4227 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
4228 }
4229 }
Marissa Wall78b72202019-03-15 14:58:34 -07004230 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004231 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004232 } else if (bufferChanged) {
4233 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004234 }
Marissa Wall78b72202019-03-15 14:58:34 -07004235 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004236 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004237 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004238 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004239 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004240 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4241 // Do not put anything that updates layer state or modifies flags after
4242 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004243 return flags;
4244}
4245
chaviw273171b2018-12-26 11:46:30 -08004246uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4247 uint32_t flags = 0;
4248 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4249 flags |= eTraversalNeeded;
4250 }
4251
chaviwa911b102019-02-14 10:18:33 -08004252 if (inputWindowCommands.syncInputWindows) {
4253 flags |= eTraversalNeeded;
4254 }
4255
Vishnu Nairec0ab382019-02-13 15:32:56 -08004256 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004257 return flags;
4258}
4259
Marissa Wall2d814fb2019-04-09 18:52:57 +00004260status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4261 uint32_t h, PixelFormat format, uint32_t flags,
4262 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004263 sp<IGraphicBufferProducer>* gbp,
4264 const sp<IBinder>& parentHandle,
4265 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004266 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004267 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004268 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004269 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004270 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004271
Robert Carrc0df3122019-04-11 13:18:21 -07004272 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4273 "Expected only one of parentLayer or parentHandle to be non-null. "
4274 "Programmer error?");
4275
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004276 status_t result = NO_ERROR;
4277
4278 sp<Layer> layer;
4279
Cody Northropbc755282017-03-31 12:00:08 -06004280 String8 uniqueName = getUniqueLayerName(name);
4281
Evan Roskya1f1e152019-01-24 16:17:46 -08004282 bool primaryDisplayOnly = false;
4283
4284 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4285 // TODO b/64227542
4286 if (metadata.has(METADATA_WINDOW_TYPE)) {
4287 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4288 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004289 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004290 primaryDisplayOnly = true;
4291 }
4292 }
4293
Mathias Agopian3165cc22012-08-08 19:42:09 -07004294 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004295 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004296 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4297 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004298
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004300 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004301 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4302 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004303 break;
chaviw13fdc492017-06-27 12:40:18 -07004304 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004305 // check if buffer size is set for color layer.
4306 if (w > 0 || h > 0) {
4307 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4308 int(w), int(h));
4309 return BAD_VALUE;
4310 }
4311
Evan Roskya1f1e152019-01-24 16:17:46 -08004312 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4313 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004314 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004315 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004316 // check if buffer size is set for container layer.
4317 if (w > 0 || h > 0) {
4318 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4319 int(w), int(h));
4320 return BAD_VALUE;
4321 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004322 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4323 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004324 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004325 default:
4326 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004327 break;
4328 }
4329
Dan Stoza7d89d062015-04-30 13:29:25 -07004330 if (result != NO_ERROR) {
4331 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004332 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004333
Evan Roskya1f1e152019-01-24 16:17:46 -08004334 if (primaryDisplayOnly) {
4335 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004336 }
4337
Robert Carrb89ea9d2018-12-10 13:01:14 -08004338 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004339 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4340 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004341 if (result != NO_ERROR) {
4342 return result;
4343 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004344 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004345
4346 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004347 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004348}
4349
Cody Northropbc755282017-03-31 12:00:08 -06004350String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4351{
4352 bool matchFound = true;
4353 uint32_t dupeCounter = 0;
4354
4355 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4356 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4357
Dan Stoza436ccf32018-06-21 12:10:12 -07004358 // Grab the state lock since we're accessing mCurrentState
4359 Mutex::Autolock lock(mStateLock);
4360
Cody Northropbc755282017-03-31 12:00:08 -06004361 // Loop over layers until we're sure there is no matching name
4362 while (matchFound) {
4363 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004364 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004365 if (layer->getName() == uniqueName) {
4366 matchFound = true;
4367 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4368 }
4369 });
4370 }
4371
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004372 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4373 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004374
4375 return uniqueName;
4376}
4377
Marissa Wallfd668622018-05-10 10:21:13 -07004378status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4379 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004380 LayerMetadata metadata, PixelFormat& format,
4381 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004382 sp<IGraphicBufferProducer>* gbp,
4383 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004384 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004385 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004386 case PIXEL_FORMAT_TRANSPARENT:
4387 case PIXEL_FORMAT_TRANSLUCENT:
4388 format = PIXEL_FORMAT_RGBA_8888;
4389 break;
4390 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004391 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004392 break;
4393 }
4394
Evan Roskya1f1e152019-01-24 16:17:46 -08004395 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4396 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004397 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004398 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004399 *handle = layer->getHandle();
4400 *gbp = layer->getProducer();
4401 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004402 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004403
Marissa Wallfd668622018-05-10 10:21:13 -07004404 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004405 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004406}
4407
Marissa Wall61c58622018-07-18 10:12:20 -07004408status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4409 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004410 LayerMetadata metadata, sp<IBinder>* handle,
4411 sp<Layer>* outLayer) {
4412 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4413 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004414 *handle = layer->getHandle();
4415 *outLayer = layer;
4416
4417 return NO_ERROR;
4418}
4419
Evan Roskya1f1e152019-01-24 16:17:46 -08004420status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4421 uint32_t h, uint32_t flags, LayerMetadata metadata,
4422 sp<IBinder>* handle, sp<Layer>* outLayer) {
4423 *outLayer = getFactory().createColorLayer(
4424 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004425 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004426 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004427}
4428
Evan Roskya1f1e152019-01-24 16:17:46 -08004429status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4430 uint32_t w, uint32_t h, uint32_t flags,
4431 LayerMetadata metadata, sp<IBinder>* handle,
4432 sp<Layer>* outLayer) {
4433 *outLayer = getFactory().createContainerLayer(
4434 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004435 *handle = (*outLayer)->getHandle();
4436 return NO_ERROR;
4437}
4438
4439
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004440void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004441 mLayersPendingRemoval.add(layer);
4442 mLayersRemoved = true;
4443 setTransactionFlags(eTransactionNeeded);
4444}
4445
Robert Carr695d5282018-12-18 15:27:58 -08004446void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004447{
Robert Carr2e102c92018-10-23 12:11:15 -07004448 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004449 // If a layer has a parent, we allow it to out-live it's handle
4450 // with the idea that the parent holds a reference and will eventually
4451 // be cleaned up. However no one cleans up the top-level so we do so
4452 // here.
4453 if (layer->getParent() == nullptr) {
4454 mCurrentState.layersSortedByZ.remove(layer);
4455 }
4456 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004457
4458 auto it = mLayersByLocalBinderToken.begin();
4459 while (it != mLayersByLocalBinderToken.end()) {
4460 if (it->second == layer) {
4461 it = mLayersByLocalBinderToken.erase(it);
4462 } else {
4463 it++;
4464 }
4465 }
4466
Robert Carr695d5282018-12-18 15:27:58 -08004467 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004468}
4469
Mathias Agopianb60314a2012-04-10 22:09:54 -07004470// ---------------------------------------------------------------------------
4471
Andy McFadden13a082e2012-08-24 10:16:42 -07004472void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004473 const auto display = getDefaultDisplayDeviceLocked();
4474 if (!display) return;
4475
4476 const sp<IBinder> token = display->getDisplayToken().promote();
4477 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004478
Jesse Hall01e29052013-02-19 16:13:35 -08004479 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004480 Vector<ComposerState> state;
4481 Vector<DisplayState> displays;
4482 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004483 d.what = DisplayState::eDisplayProjectionChanged |
4484 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004485 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004486 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004487 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004488 d.frame.makeInvalid();
4489 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004490 d.width = 0;
4491 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004492 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004493 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004494
Dominik Laskowskie9774092018-12-11 10:04:24 -08004495 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004496
Dominik Laskowski83b88212018-12-11 13:34:06 -08004497 const nsecs_t vsyncPeriod = getVsyncPeriod();
4498 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004499
Brian Andersond0010582017-03-07 13:20:31 -08004500 // Use phase of 0 since phase is not known.
4501 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004502 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004503 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004504}
4505
4506void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004507 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004508 postMessageAsync(
4509 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004510}
4511
Ady Abraham27c70212019-06-11 10:52:26 -07004512void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4513 if (mHWCVsyncState != enabled) {
4514 getHwComposer().setVsyncEnabled(displayId, enabled);
4515 mHWCVsyncState = enabled;
4516 }
4517}
4518
Dominik Laskowskie9774092018-12-11 10:04:24 -08004519void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004520 if (display->isVirtual()) {
4521 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004522 return;
4523 }
4524
Dominik Laskowski075d3172018-05-24 15:50:06 -07004525 const auto displayId = display->getId();
4526 LOG_ALWAYS_FATAL_IF(!displayId);
4527
Dominik Laskowski34157762018-10-31 13:07:19 -07004528 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004529
4530 int currentMode = display->getPowerMode();
4531 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004532 return;
4533 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004534
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004535 display->setPowerMode(mode);
4536
Lloyd Pique4dccc412018-01-22 17:21:36 -08004537 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004538 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004539 }
4540
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004541 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004542 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004543 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004544 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004545 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004546 mScheduler->onScreenAcquired(mAppConnectionHandle);
4547 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004548 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004549
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004550 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004551 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004552 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004553
4554 struct sched_param param = {0};
4555 param.sched_priority = 1;
4556 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4557 ALOGW("Couldn't set SCHED_FIFO on display on");
4558 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004559 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004560 // Turn off the display
4561 struct sched_param param = {0};
4562 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4563 ALOGW("Couldn't set SCHED_OTHER on display off");
4564 }
4565
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004566 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004567 mScheduler->disableHardwareVsync(true);
4568 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004569 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004570
Ady Abraham27c70212019-06-11 10:52:26 -07004571 // Make sure HWVsync is disabled before turning off the display
4572 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4573
Dominik Laskowski075d3172018-05-24 15:50:06 -07004574 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004575 mVisibleRegionsDirty = true;
4576 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004577 } else if (mode == HWC_POWER_MODE_DOZE ||
4578 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004579 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004580 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004581 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004582 mScheduler->onScreenAcquired(mAppConnectionHandle);
4583 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004584 }
4585 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4586 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004587 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004588 mScheduler->disableHardwareVsync(true);
4589 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004590 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004591 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004592 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004593 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004594 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004595 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004596
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004597 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004598 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004599 mRefreshRateStats.setPowerMode(mode);
Ady Abraham24363172019-07-12 12:37:57 -07004600 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004601 }
4602
Dominik Laskowski34157762018-10-31 13:07:19 -07004603 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004604}
4605
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004606void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004607 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004608 const auto display = getDisplayDevice(displayToken);
4609 if (!display) {
4610 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4611 displayToken.get());
4612 } else if (display->isVirtual()) {
4613 ALOGW("Attempt to set power mode %d for virtual display", mode);
4614 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004615 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004616 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004617 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004618}
4619
4620// ---------------------------------------------------------------------------
4621
Dominik Laskowskic2867142019-01-21 11:33:38 -08004622status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4623 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004624 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004625
Mathias Agopianbd115332013-04-18 16:41:04 -07004626 IPCThreadState* ipc = IPCThreadState::self();
4627 const int pid = ipc->getCallingPid();
4628 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004629
Mathias Agopianbd115332013-04-18 16:41:04 -07004630 if ((uid != AID_SHELL) &&
4631 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004632 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4633 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004634 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004635 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004636 // (this would indicate SF is stuck, but we want to be able to
4637 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004638 status_t err = mStateLock.timedLock(s2ns(1));
4639 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004640 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result,
4642 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4643 "(no locks held)\n",
4644 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004645 }
4646
Dominik Laskowskic2867142019-01-21 11:33:38 -08004647 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004648
Dominik Laskowskic2867142019-01-21 11:33:38 -08004649 static const std::unordered_map<std::string, Dumper> dumpers = {
4650 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4651 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4652 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004653 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004654 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004655 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004656 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4657 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004658 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4659 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4660 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4661 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4662 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4663 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004664 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004665 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4666 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004667
Dominik Laskowskic2867142019-01-21 11:33:38 -08004668 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004669
Dominik Laskowskic2867142019-01-21 11:33:38 -08004670 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4671 (it->second)(args, asProto, result);
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004672 } else if (!asProto) {
4673 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004674 }
4675
Mathias Agopian9795c422009-08-26 16:36:26 -07004676 if (locked) {
4677 mStateLock.unlock();
4678 }
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004679
4680 LayersProto layersProto = dumpProtoFromMainThread();
4681 if (asProto) {
4682 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4683 } else {
4684 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4685 result.append(LayerProtoParser::layerTreeToString(layerTree));
4686 result.append("\n");
4687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004688 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004690 return NO_ERROR;
4691}
4692
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004693status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4694 if (asProto && mTracing.isEnabled()) {
4695 mTracing.writeToFileAsync();
4696 }
4697
4698 return doDump(fd, DumpArgs(), asProto);
4699}
4700
Dominik Laskowskic2867142019-01-21 11:33:38 -08004701void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004702 mCurrentState.traverseInZOrder(
4703 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004704}
4705
Dominik Laskowskic2867142019-01-21 11:33:38 -08004706void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004707 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004708
Dominik Laskowskic2867142019-01-21 11:33:38 -08004709 if (args.size() > 1) {
4710 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004711 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004712 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004713 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004714 }
Robert Carr2047fae2016-11-28 14:09:09 -08004715 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004716 } else {
4717 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004718 }
4719}
4720
Dominik Laskowskic2867142019-01-21 11:33:38 -08004721void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004722 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004723 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004724 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004725 }
Robert Carr2047fae2016-11-28 14:09:09 -08004726 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004727
Svetoslavd85084b2014-03-20 10:28:31 -07004728 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004729}
4730
Dominik Laskowskic2867142019-01-21 11:33:38 -08004731void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4732 mTimeStats->parseArgs(asProto, args, result);
4733}
4734
Jamie Gennis6547ff42013-07-16 20:12:42 -07004735// This should only be called from the main thread. Otherwise it would need
4736// the lock and should use mCurrentState rather than mDrawingState.
4737void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004738 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004739 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004740 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004741
4742 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4743}
4744
Yiwei Zhang5434a782018-12-05 18:06:32 -08004745void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004746 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004747
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004748 if (isLayerTripleBufferingDisabled())
4749 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004750
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4752 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4753 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4754 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4755 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4756 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004757 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004758}
4759
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004760void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004761 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004762 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004763 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004764 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004765
Ady Abraham97d04232019-03-05 19:48:12 -08004766 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004767 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4768 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004769 StringAppendF(&result, "Allowed Display Configs: ");
4770 for (int32_t configId : mAllowedDisplayConfigs) {
4771 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4772 if (refresh.second && refresh.second->configId == configId) {
4773 StringAppendF(&result, "%dHz, ", refresh.second->fps);
4774 }
4775 }
4776 }
4777 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4778 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004779 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004780}
4781
Yiwei Zhang5434a782018-12-05 18:06:32 -08004782void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4783 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004784 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4785 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004786 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004787 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004788 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004789 }
David Sodman4a36e932017-11-07 14:29:47 -08004790 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004791 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004792 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4794 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004795}
4796
Dan Stozae77c7662016-05-13 11:37:28 -07004797void SurfaceFlinger::recordBufferingStats(const char* layerName,
4798 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004799 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4800 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004801 for (const auto& segment : history) {
4802 if (!segment.usedThirdBuffer) {
4803 stats.twoBufferTime += segment.totalTime;
4804 }
4805 if (segment.occupancyAverage < 1.0f) {
4806 stats.doubleBufferedTime += segment.totalTime;
4807 } else if (segment.occupancyAverage < 2.0f) {
4808 stats.tripleBufferedTime += segment.totalTime;
4809 }
4810 ++stats.numSegments;
4811 stats.totalTime += segment.totalTime;
4812 }
4813}
4814
Yiwei Zhang5434a782018-12-05 18:06:32 -08004815void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4816 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004817
4818 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4819 const size_t count = currentLayers.size();
4820 for (size_t i=0 ; i<count ; i++) {
4821 currentLayers[i]->dumpFrameEvents(result);
4822 }
4823}
4824
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004826 result.append("Buffering stats:\n");
4827 result.append(" [Layer name] <Active time> <Two buffer> "
4828 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004829 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004830 typedef std::tuple<std::string, float, float, float> BufferTuple;
4831 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004832 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004833 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004834 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004835 if (stats.numSegments == 0) {
4836 continue;
4837 }
4838 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4839 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4840 stats.totalTime;
4841 float doubleBufferRatio = static_cast<float>(
4842 stats.doubleBufferedTime) / stats.totalTime;
4843 float tripleBufferRatio = static_cast<float>(
4844 stats.tripleBufferedTime) / stats.totalTime;
4845 sorted.insert({activeTime, {name, twoBufferRatio,
4846 doubleBufferRatio, tripleBufferRatio}});
4847 }
4848 for (const auto& sortedPair : sorted) {
4849 float activeTime = sortedPair.first;
4850 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004851 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4852 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004853 }
4854 result.append("\n");
4855}
4856
Yiwei Zhang5434a782018-12-05 18:06:32 -08004857void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004858 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004859 const auto displayId = display->getId();
4860 if (!displayId) {
4861 continue;
4862 }
4863 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004864 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004865 continue;
4866 }
4867
Yiwei Zhang5434a782018-12-05 18:06:32 -08004868 StringAppendF(&result,
4869 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4870 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004871 uint8_t port;
4872 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004873 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004874 result.append("no identification data\n");
4875 continue;
4876 }
4877
4878 if (!isEdid(data)) {
4879 result.append("unknown identification data: ");
4880 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004881 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004882 }
4883 result.append("\n");
4884 continue;
4885 }
4886
4887 const auto edid = parseEdid(data);
4888 if (!edid) {
4889 result.append("invalid EDID: ");
4890 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004891 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004892 }
4893 result.append("\n");
4894 continue;
4895 }
4896
Yiwei Zhang5434a782018-12-05 18:06:32 -08004897 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004898 result.append(edid->displayName.data(), edid->displayName.length());
4899 result.append("\"\n");
4900 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004901}
4902
Yiwei Zhang5434a782018-12-05 18:06:32 -08004903void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004904 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004905 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4906 StringAppendF(&result, "DisplayColorSetting: %s\n",
4907 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004908
4909 // TODO: print out if wide-color mode is active or not
4910
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004911 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004912 const auto displayId = display->getId();
4913 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004914 continue;
4915 }
4916
Yiwei Zhang5434a782018-12-05 18:06:32 -08004917 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004918 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004919 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004920 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004921 }
4922
Lloyd Pique32cbe282018-10-19 13:09:22 -07004923 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004924 StringAppendF(&result, " Current color mode: %s (%d)\n",
4925 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004926 }
4927 result.append("\n");
4928}
4929
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004930LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004931 LayersProto layersProto;
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004932 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004933 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004934 layer->writeToProtoDrawingState(layerProto, traceFlags);
4935 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004936 });
4937
4938 return layersProto;
4939}
4940
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004941LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4942 LayersProto layersProto;
4943 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4944 return layersProto;
4945}
4946
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004947LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4948 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004949 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004950
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004951 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004952 resolution->set_w(displayDevice->getWidth());
4953 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004954
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004955 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004956 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004957
Lloyd Pique32cbe282018-10-19 13:09:22 -07004958 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4959 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4960 layersProto.set_global_transform(displayState.orientation);
4961
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004962 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004963 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004964 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004965 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004966 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nairb57b01e2019-09-16 18:22:19 +02004967 layer->writeToProtoCompositionState(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004968 }
4969 });
4970
4971 return layersProto;
4972}
4973
Dominik Laskowskic2867142019-01-21 11:33:38 -08004974void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4975 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004976 Colorizer colorizer(colorize);
4977
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004978 // figure out if we're stuck somewhere
4979 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004980 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004981 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4982
4983 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004984 * Dump library configuration.
4985 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004986
4987 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004988 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004989 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004990 appendSfConfigString(result);
4991 appendUiConfigString(result);
4992 appendGuiConfigString(result);
4993 result.append("\n");
4994
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004995 result.append("\nDisplay identification data:\n");
4996 dumpDisplayIdentificationData(result);
4997
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004998 result.append("\nWide-Color information:\n");
4999 dumpWideColorInfo(result);
5000
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005001 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005002 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005003 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07005004 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005005 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07005006
Andy McFadden41d67d72014-04-25 16:58:34 -07005007 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005008 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07005009 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005010 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08005011 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08005012
Dan Stozab90cf072015-03-05 11:05:59 -08005013 dumpStaticScreenStats(result);
5014 result.append("\n");
5015
Alec Mouri40189b02019-03-05 15:07:54 -08005016 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
5017 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
5018 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07005019
Dan Stozae77c7662016-05-13 11:37:28 -07005020 dumpBufferingStats(result);
5021
Andy McFadden4803b742012-09-24 19:07:20 -07005022 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005023 * Dump the visible layer list
5024 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005025 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005026 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
5027 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
5028 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005029 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005030
Chia-I Wu2f884132018-09-13 15:17:58 -07005031 {
Lloyd Pique207def92019-02-28 16:09:52 -08005032 StringAppendF(&result, "Composition layers\n");
5033 mDrawingState.traverseInZOrder([&](Layer* layer) {
5034 auto compositionLayer = layer->getCompositionLayer();
5035 if (compositionLayer) compositionLayer->dump(result);
5036 });
5037 }
5038
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005039 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005040 * Dump Display state
5041 */
5042
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005043 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005044 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005045 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005046 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005047 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005048 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005049 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005050
5051 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005052 * Dump SurfaceFlinger global state
5053 */
5054
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005055 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005056 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005057 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005058
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005059 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005060
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005061 DebugEGLImageTracker::getInstance()->dump(result);
5062
Dominik Laskowski075d3172018-05-24 15:50:06 -07005063 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005064 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5065 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005066 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5067 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005068 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005069 StringAppendF(&result,
5070 " transaction-flags : %08x\n"
5071 " gpu_to_cpu_unsupported : %d\n",
5072 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005073
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005074 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005075 displayId && getHwComposer().isConnected(*displayId)) {
5076 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005077 StringAppendF(&result,
5078 " refresh-rate : %f fps\n"
5079 " x-dpi : %f\n"
5080 " y-dpi : %f\n",
5081 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5082 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005083 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005084
Yiwei Zhang5434a782018-12-05 18:06:32 -08005085 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005086
Dan Stozae22aec72016-08-01 13:20:59 -07005087 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005088 * Tracing state
5089 */
5090 mTracing.dump(result);
5091 result.append("\n");
5092
5093 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005094 * HWC layer minidump
5095 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005096 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005097 const auto displayId = display->getId();
5098 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005099 continue;
5100 }
5101
Yiwei Zhang5434a782018-12-05 18:06:32 -08005102 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005103 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005104 const sp<DisplayDevice> displayDevice = display;
5105 mCurrentState.traverseInZOrder(
5106 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005107 result.append("\n");
5108 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005109
5110 /*
5111 * Dump HWComposer state
5112 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005113 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005114 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005115 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005116 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005117 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005118 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005119
5120 /*
5121 * Dump gralloc state
5122 */
5123 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5124 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005125
5126 /*
5127 * Dump VrFlinger state if in use.
5128 */
5129 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5130 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005131 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005132 result.append("\n");
5133 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005134
5135 /**
5136 * Scheduler dump state.
5137 */
Ana Krulecc2870422019-01-29 19:00:58 -08005138 result.append("\nScheduler state:\n");
5139 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005140 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005141 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005142
5143 result.append(mTimeStats->miniDump());
5144 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005145}
5146
Dominik Laskowski075d3172018-05-24 15:50:06 -07005147const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005148 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005149 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005150 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005151 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005152 }
5153 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005154
Dominik Laskowski34157762018-10-31 13:07:19 -07005155 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005156 static const Vector<sp<Layer>> empty;
5157 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005158}
5159
Chia-I Wu28f320b2018-05-03 11:02:56 -07005160void SurfaceFlinger::updateColorMatrixLocked() {
5161 mat4 colorMatrix;
5162 if (mGlobalSaturationFactor != 1.0f) {
5163 // Rec.709 luma coefficients
5164 float3 luminance{0.213f, 0.715f, 0.072f};
5165 luminance *= 1.0f - mGlobalSaturationFactor;
5166 mat4 saturationMatrix = mat4(
5167 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5168 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5169 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5170 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5171 );
5172 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5173 } else {
5174 colorMatrix = mClientColorMatrix * mDaltonizer();
5175 }
5176
5177 if (mCurrentState.colorMatrix != colorMatrix) {
5178 mCurrentState.colorMatrix = colorMatrix;
5179 mCurrentState.colorMatrixChanged = true;
5180 setTransactionFlags(eTransactionNeeded);
5181 }
5182}
5183
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005184status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005185#pragma clang diagnostic push
5186#pragma clang diagnostic error "-Wswitch-enum"
5187 switch (static_cast<ISurfaceComposerTag>(code)) {
5188 // These methods should at minimum make sure that the client requested
5189 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005190 case BOOT_FINISHED:
5191 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005192 case CREATE_DISPLAY:
5193 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005194 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005195 case GET_ANIMATION_FRAME_STATS:
5196 case GET_HDR_CAPABILITIES:
5197 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005198 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005199 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005200 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005201 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005202 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005203 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005204 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005205 case GET_DISPLAYED_CONTENT_SAMPLE:
5206 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005207 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5208 IPCThreadState* ipc = IPCThreadState::self();
5209 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5210 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005211 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005212 }
Robert Carr1db73f62016-12-21 12:58:51 -08005213 return OK;
5214 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005215 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005216 IPCThreadState* ipc = IPCThreadState::self();
5217 const int pid = ipc->getCallingPid();
5218 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005219 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5220 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005221 return PERMISSION_DENIED;
5222 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005223 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005224 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005225 // Used by apps to hook Choreographer to SurfaceFlinger.
5226 case CREATE_DISPLAY_EVENT_CONNECTION:
5227 // The following calls are currently used by clients that do not
5228 // request necessary permissions. However, they do not expose any secret
5229 // information, so it is OK to pass them.
5230 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005231 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005232 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005233 case GET_PHYSICAL_DISPLAY_IDS:
5234 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005235 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005236 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005237 case GET_DISPLAY_CONFIGS:
5238 case GET_DISPLAY_STATS:
5239 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5240 // Calling setTransactionState is safe, because you need to have been
5241 // granted a reference to Client* and Handle* to do anything with it.
5242 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005243 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005244 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005245 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005246 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005247 case IS_WIDE_COLOR_DISPLAY:
5248 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5249 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005250 return OK;
5251 }
5252 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005253 case CAPTURE_SCREEN:
5254 case ADD_REGION_SAMPLING_LISTENER:
5255 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005256 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005257 IPCThreadState* ipc = IPCThreadState::self();
5258 const int pid = ipc->getCallingPid();
5259 const int uid = ipc->getCallingUid();
5260 if ((uid != AID_GRAPHICS) &&
5261 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5262 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5263 return PERMISSION_DENIED;
5264 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005265 return OK;
5266 }
5267 // The following codes are deprecated and should never be allowed to access SF.
5268 case CONNECT_DISPLAY_UNUSED:
5269 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5270 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5271 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005272 }
chaviw93df2ea2019-04-30 16:45:12 -07005273 case CAPTURE_SCREEN_BY_ID: {
5274 IPCThreadState* ipc = IPCThreadState::self();
5275 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005276 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005277 return OK;
5278 }
5279 return PERMISSION_DENIED;
5280 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005281 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005282
5283 // These codes are used for the IBinder protocol to either interrogate the recipient
5284 // side of the transaction for its canonical interface descriptor or to dump its state.
5285 // We let them pass by default.
5286 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5287 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5288 code == IBinder::SYSPROPS_TRANSACTION) {
5289 return OK;
5290 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005291 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005292 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005293 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005294 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5295 return OK;
5296 }
5297 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5298 return PERMISSION_DENIED;
5299#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005300}
5301
Ana Krulec13be8ad2018-08-21 02:43:56 +00005302status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5303 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005304 status_t credentialCheck = CheckTransactCodeCredentials(code);
5305 if (credentialCheck != OK) {
5306 return credentialCheck;
5307 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005309 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5310 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005311 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005312 IPCThreadState* ipc = IPCThreadState::self();
5313 const int uid = ipc->getCallingUid();
5314 if (CC_UNLIKELY(uid != AID_SYSTEM
5315 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005316 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005317 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005318 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005319 return PERMISSION_DENIED;
5320 }
5321 int n;
5322 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005323 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005324 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005325 return NO_ERROR;
5326 case 1002: // SHOW_UPDATES
5327 n = data.readInt32();
5328 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005329 invalidateHwcGeometry();
5330 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005331 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005332 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005333 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005334 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005335 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005336 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005337 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005338 setTransactionFlags(
5339 eTransactionNeeded|
5340 eDisplayTransactionNeeded|
5341 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005342 return NO_ERROR;
5343 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005344 case 1006:{ // send empty update
5345 signalRefresh();
5346 return NO_ERROR;
5347 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005348 case 1008: // toggle use of hw composer
5349 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005350 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005351 invalidateHwcGeometry();
5352 repaintEverything();
5353 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005354 case 1009: // toggle use of transform hint
5355 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005356 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005357 invalidateHwcGeometry();
5358 repaintEverything();
5359 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005360 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005361 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005362 reply->writeInt32(0);
5363 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005364 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005365 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005366 return NO_ERROR;
5367 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005368 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005369 if (!display) {
5370 return NAME_NOT_FOUND;
5371 }
5372
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005373 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005374 return NO_ERROR;
5375 }
5376 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005377 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005378 // daltonize
5379 n = data.readInt32();
5380 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005381 case 1:
5382 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5383 break;
5384 case 2:
5385 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5386 break;
5387 case 3:
5388 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5389 break;
5390 default:
5391 mDaltonizer.setType(ColorBlindnessType::None);
5392 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005393 }
5394 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005395 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005396 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005397 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005398 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005399
5400 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005401 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005402 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005403 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005404 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005405 // apply a color matrix
5406 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005407 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005408 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005409 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005410 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005411 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005412 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005413 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005414 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005415 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005416 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005417
5418 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5419 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005420 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005421 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5422 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5423 }
5424
Chia-I Wu28f320b2018-05-03 11:02:56 -07005425 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005426 return NO_ERROR;
5427 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005428 // This is an experimental interface
5429 // Needs to be shifted to proper binder interface when we productize
5430 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005431 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005432 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005433 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005434 return NO_ERROR;
5435 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005436 case 1017: {
5437 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005438 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005439 return NO_ERROR;
5440 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005441 case 1018: { // Modify Choreographer's phase offset
5442 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005443 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005444 return NO_ERROR;
5445 }
5446 case 1019: { // Modify SurfaceFlinger's phase offset
5447 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005448 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005449 return NO_ERROR;
5450 }
Irvel468051e2016-06-13 16:44:44 -07005451 case 1020: { // Layer updates interceptor
5452 n = data.readInt32();
5453 if (n) {
5454 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005455 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005456 }
5457 else{
5458 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005459 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005460 }
5461 return NO_ERROR;
5462 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005463 case 1021: { // Disable HWC virtual displays
5464 n = data.readInt32();
5465 mUseHwcVirtualDisplays = !n;
5466 return NO_ERROR;
5467 }
Romain Guy0147a172017-06-01 13:53:56 -07005468 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005469 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005470 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005471
Chia-I Wu28f320b2018-05-03 11:02:56 -07005472 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005473 return NO_ERROR;
5474 }
Romain Guy54f154a2017-10-24 21:40:32 +01005475 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005476 int32_t colorMode;
5477
Chia-I Wu0d711262018-05-21 15:19:35 -07005478 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005479 if (data.readInt32(&colorMode) == NO_ERROR) {
5480 mForceColorMode = static_cast<ColorMode>(colorMode);
5481 }
Romain Guy54f154a2017-10-24 21:40:32 +01005482 invalidateHwcGeometry();
5483 repaintEverything();
5484 return NO_ERROR;
5485 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005486 // Deprecate, use 1030 to check whether the device is color managed.
5487 case 1024: {
5488 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005489 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005490 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005491 n = data.readInt32();
5492 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005493 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005494 Mutex::Autolock lock(mStateLock);
5495 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005496 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005497 reply->writeInt32(NO_ERROR);
5498 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005499 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005500 bool writeFile = false;
5501 {
5502 Mutex::Autolock lock(mStateLock);
5503 mTracingEnabledChanged = true;
5504 writeFile = mTracing.disable();
5505 }
5506
5507 if (writeFile) {
5508 reply->writeInt32(mTracing.writeToFile());
5509 } else {
5510 reply->writeInt32(NO_ERROR);
5511 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005512 }
5513 return NO_ERROR;
5514 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005515 case 1026: { // Get layer tracing status
5516 reply->writeBool(mTracing.isEnabled());
5517 return NO_ERROR;
5518 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005519 // Is a DisplayColorSetting supported?
5520 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005521 const auto display = getDefaultDisplayDevice();
5522 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005523 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005524 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005525
5526 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5527 switch (setting) {
5528 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005529 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005530 break;
5531 case DisplayColorSetting::UNMANAGED:
5532 reply->writeBool(true);
5533 break;
5534 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005535 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005536 break;
5537 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005538 reply->writeBool(
5539 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005540 break;
5541 }
5542 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005543 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005544 // Is VrFlinger active?
5545 case 1028: {
5546 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005547 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005548 return NO_ERROR;
5549 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005550 // Set buffer size for SF tracing (value in KB)
5551 case 1029: {
5552 n = data.readInt32();
5553 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5554 ALOGW("Invalid buffer size: %d KB", n);
5555 reply->writeInt32(BAD_VALUE);
5556 return BAD_VALUE;
5557 }
5558
5559 ALOGD("Updating trace buffer to %d KB", n);
5560 mTracing.setBufferSize(n * 1024);
5561 reply->writeInt32(NO_ERROR);
5562 return NO_ERROR;
5563 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005564 // Is device color managed?
5565 case 1030: {
5566 reply->writeBool(useColorManagement);
5567 return NO_ERROR;
5568 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005569 // Override default composition data space
5570 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5571 // && adb shell stop zygote && adb shell start zygote
5572 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5573 // adb shell stop zygote && adb shell start zygote
5574 case 1031: {
5575 Mutex::Autolock _l(mStateLock);
5576 n = data.readInt32();
5577 if (n) {
5578 n = data.readInt32();
5579 if (n) {
5580 Dataspace dataspace = static_cast<Dataspace>(n);
5581 if (!validateCompositionDataspace(dataspace)) {
5582 return BAD_VALUE;
5583 }
5584 mDefaultCompositionDataspace = dataspace;
5585 }
5586 n = data.readInt32();
5587 if (n) {
5588 Dataspace dataspace = static_cast<Dataspace>(n);
5589 if (!validateCompositionDataspace(dataspace)) {
5590 return BAD_VALUE;
5591 }
5592 mWideColorGamutCompositionDataspace = dataspace;
5593 }
5594 } else {
5595 // restore composition data space.
5596 mDefaultCompositionDataspace = defaultCompositionDataspace;
5597 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5598 }
5599 return NO_ERROR;
5600 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005601 // Set trace flags
5602 case 1033: {
5603 n = data.readUint32();
5604 ALOGD("Updating trace flags to 0x%x", n);
5605 mTracing.setTraceFlags(n);
5606 reply->writeInt32(NO_ERROR);
5607 return NO_ERROR;
5608 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005609 case 1034: {
5610 // TODO(b/129297325): expose this via developer menu option
5611 n = data.readInt32();
5612 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005613 RefreshRateType type;
5614 {
5615 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5616 type = mDesiredActiveConfig.type;
5617 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005618 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005619 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005620 } else if (!n) {
5621 mRefreshRateOverlay.reset();
5622 }
5623 return NO_ERROR;
5624 }
Ady Abraham34392f72019-04-10 11:29:27 -07005625 case 1035: {
5626 n = data.readInt32();
5627 mDebugDisplayConfigSetByBackdoor = false;
5628 if (n >= 0) {
5629 const auto displayToken = getInternalDisplayToken();
5630 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5631 if (result != NO_ERROR) {
5632 return result;
5633 }
5634 mDebugDisplayConfigSetByBackdoor = true;
5635 }
5636 return NO_ERROR;
5637 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005638 }
5639 }
5640 return err;
5641}
5642
Steven Thomas6d8110b2017-08-31 18:24:21 -07005643void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005644 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005645 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005646}
5647
Ana Krulec7d1d6832018-12-27 11:10:09 -08005648void SurfaceFlinger::repaintEverythingForHWC() {
5649 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005650 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005651}
5652
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005653// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5654class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005655public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005656 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5657 ~WindowDisconnector() {
5658 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005659 }
5660
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005661private:
5662 ANativeWindow* mWindow;
5663 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005664};
5665
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005666status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005667 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5668 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005669 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005670 uint32_t reqWidth, uint32_t reqHeight,
5671 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005672 ISurfaceComposer::Rotation rotation,
5673 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005674 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005675
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005676 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005677
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005678 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5679
Chia-I Wu20261cb2018-08-23 12:55:44 -07005680 sp<DisplayDevice> display;
5681 {
5682 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005683
Chia-I Wu20261cb2018-08-23 12:55:44 -07005684 display = getDisplayDeviceLocked(displayToken);
5685 if (!display) return BAD_VALUE;
5686
Chia-I Wucb023152018-08-28 12:57:23 -07005687 // set the requested width/height to the logical display viewport size
5688 // by default
5689 if (reqWidth == 0 || reqHeight == 0) {
5690 reqWidth = uint32_t(display->getViewport().width());
5691 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005692 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005693 }
5694
Peiyong Lin0e003c92018-09-17 11:09:51 -07005695 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005696 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005697
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005698 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5699 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005700 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005701 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005702}
5703
chaviw93df2ea2019-04-30 16:45:12 -07005704static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5705 switch (colorMode) {
5706 case ColorMode::DISPLAY_P3:
5707 case ColorMode::BT2100_PQ:
5708 case ColorMode::BT2100_HLG:
5709 case ColorMode::DISPLAY_BT2020:
5710 return Dataspace::DISPLAY_P3;
5711 default:
5712 return Dataspace::V0_SRGB;
5713 }
5714}
5715
5716const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5717 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5718 if (displayToken) {
5719 return getDisplayDeviceLocked(displayToken);
5720 }
5721 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5722 // may not have a displayId.
5723 for (const auto& [token, display] : mDisplays) {
5724 if (display->getLayerStack() == displayOrLayerStack) {
5725 return display;
5726 }
5727 }
5728 return nullptr;
5729}
5730
5731status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5732 sp<GraphicBuffer>* outBuffer) {
5733 sp<DisplayDevice> display;
5734 uint32_t width;
5735 uint32_t height;
5736 ui::Transform::orientation_flags captureOrientation;
5737 {
5738 Mutex::Autolock _l(mStateLock);
5739 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5740 if (!display) {
5741 return BAD_VALUE;
5742 }
5743
5744 width = uint32_t(display->getViewport().width());
5745 height = uint32_t(display->getViewport().height());
5746
5747 captureOrientation = fromSurfaceComposerRotation(
5748 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005749 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5750 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5751 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5752 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5753 }
chaviw93df2ea2019-04-30 16:45:12 -07005754 *outDataspace =
5755 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5756 }
5757
5758 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5759 false /* captureSecureLayers */);
5760
5761 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5762 std::placeholders::_1);
5763 bool ignored = false;
5764 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5765 false /* useIdentityTransform */,
5766 ignored /* outCapturedSecureLayers */);
5767}
5768
Robert Carr866455f2019-04-02 16:28:26 -07005769status_t SurfaceFlinger::captureLayers(
5770 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5771 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5772 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5773 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005774 ATRACE_CALL();
5775
5776 class LayerRenderArea : public RenderArea {
5777 public:
Robert Carr578038f2018-03-09 12:25:24 -08005778 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005779 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5780 bool childrenOnly)
5781 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005782 mLayer(layer),
5783 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005784 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005785 mFlinger(flinger),
5786 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005787 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005788 Rect getBounds() const override {
5789 const Layer::State& layerState(mLayer->getDrawingState());
5790 return mLayer->getBufferSize(layerState);
5791 }
Marissa Wall61c58622018-07-18 10:12:20 -07005792 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005793 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005794 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005795 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005796 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005797 }
chaviwa76b2712017-09-20 12:02:26 -07005798 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005799 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005800 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005801 Rect getSourceCrop() const override {
5802 if (mCrop.isEmpty()) {
5803 return getBounds();
5804 } else {
5805 return mCrop;
5806 }
5807 }
Robert Carr578038f2018-03-09 12:25:24 -08005808 class ReparentForDrawing {
5809 public:
5810 const sp<Layer>& oldParent;
5811 const sp<Layer>& newParent;
5812
Vishnu Nair4351ad52019-02-11 14:13:02 -08005813 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5814 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005815 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005816 // Compute and cache the bounds for the new parent layer.
5817 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005818 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005819 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005820 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005821 };
5822
5823 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005824 const Rect sourceCrop = getSourceCrop();
5825 // no need to check rotation because there is none
5826 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5827 sourceCrop.height() != getReqHeight();
5828
Robert Carr578038f2018-03-09 12:25:24 -08005829 if (!mChildrenOnly) {
5830 mTransform = mLayer->getTransform().inverse();
5831 drawLayers();
5832 } else {
5833 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005834 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005835 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005836 bounds.getWidth(), bounds.getHeight(), 0,
5837 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005838
Vishnu Nair4351ad52019-02-11 14:13:02 -08005839 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005840 drawLayers();
5841 }
5842 }
chaviwa76b2712017-09-20 12:02:26 -07005843
chaviwa76b2712017-09-20 12:02:26 -07005844 private:
chaviw7206d492017-11-10 16:16:12 -08005845 const sp<Layer> mLayer;
5846 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005847
5848 // In the "childrenOnly" case we reparent the children to a screenshot
5849 // layer which has no properties set and which does not draw.
5850 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005851 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005852 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005853
5854 SurfaceFlinger* mFlinger;
5855 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005856 };
5857
Robert Carrc0df3122019-04-11 13:18:21 -07005858 int reqWidth = 0;
5859 int reqHeight = 0;
5860 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005861 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005862 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005863
Robert Carrc0df3122019-04-11 13:18:21 -07005864 {
5865 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005866
Robert Carrc0df3122019-04-11 13:18:21 -07005867 parent = fromHandle(layerHandleBinder);
5868 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5869 ALOGE("captureLayers called with an invalid or removed parent");
5870 return NAME_NOT_FOUND;
5871 }
5872
5873 const int uid = IPCThreadState::self()->getCallingUid();
5874 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5875 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5876 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5877 return PERMISSION_DENIED;
5878 }
5879
5880 if (sourceCrop.width() <= 0) {
5881 crop.left = 0;
5882 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5883 }
5884
5885 if (sourceCrop.height() <= 0) {
5886 crop.top = 0;
5887 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5888 }
5889 reqWidth = crop.width() * frameScale;
5890 reqHeight = crop.height() * frameScale;
5891
5892 for (const auto& handle : excludeHandles) {
5893 sp<Layer> excludeLayer = fromHandle(handle);
5894 if (excludeLayer != nullptr) {
5895 excludeLayers.emplace(excludeLayer);
5896 } else {
5897 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5898 return NAME_NOT_FOUND;
5899 }
5900 }
5901 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005902
Chia-I Wu20261cb2018-08-23 12:55:44 -07005903 // really small crop or frameScale
5904 if (reqWidth <= 0) {
5905 reqWidth = 1;
5906 }
5907 if (reqHeight <= 0) {
5908 reqHeight = 1;
5909 }
5910
Robert Carr866455f2019-04-02 16:28:26 -07005911 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5912 auto traverseLayers = [parent, childrenOnly,
5913 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005914 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5915 if (!layer->isVisible()) {
5916 return;
Robert Carr578038f2018-03-09 12:25:24 -08005917 } else if (childrenOnly && layer == parent.get()) {
5918 return;
chaviwa76b2712017-09-20 12:02:26 -07005919 }
Robert Carr866455f2019-04-02 16:28:26 -07005920
5921 sp<Layer> p = layer;
5922 while (p != nullptr) {
5923 if (excludeLayers.count(p) != 0) {
5924 return;
5925 }
5926 p = p->getParent();
5927 }
5928
chaviwa76b2712017-09-20 12:02:26 -07005929 visitor(layer);
5930 });
5931 };
Robert Carr108b2c72019-04-02 16:32:58 -07005932
5933 bool outCapturedSecureLayers = false;
5934 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5935 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005936}
5937
5938status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5939 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005940 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005941 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005942 bool useIdentityTransform,
5943 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005944 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005945
Peiyong Lin0e003c92018-09-17 11:09:51 -07005946 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005947 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5948 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005949 *outBuffer =
5950 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5951 static_cast<android_pixel_format>(reqPixelFormat), 1,
5952 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005953
Robert Carr108b2c72019-04-02 16:32:58 -07005954 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5955 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005956}
5957
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005958status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5959 TraverseLayersFunction traverseLayers,
5960 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005961 bool useIdentityTransform,
5962 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005963 // This mutex protects syncFd and captureResult for communication of the return values from the
5964 // main thread back to this Binder thread
5965 std::mutex captureMutex;
5966 std::condition_variable captureCondition;
5967 std::unique_lock<std::mutex> captureLock(captureMutex);
5968 int syncFd = -1;
5969 std::optional<status_t> captureResult;
5970
Robert Carr03480e22018-01-04 16:02:06 -08005971 const int uid = IPCThreadState::self()->getCallingUid();
5972 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5973
Dominik Laskowski8c001672018-05-30 16:52:06 -07005974 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005975 // If there is a refresh pending, bug out early and tell the binder thread to try again
5976 // after the refresh.
5977 if (mRefreshPending) {
5978 ATRACE_NAME("Skipping screenshot for now");
5979 std::unique_lock<std::mutex> captureLock(captureMutex);
5980 captureResult = std::make_optional<status_t>(EAGAIN);
5981 captureCondition.notify_one();
5982 return;
5983 }
5984
5985 status_t result = NO_ERROR;
5986 int fd = -1;
5987 {
5988 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005989 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005990 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005991 useIdentityTransform, forSystem, &fd,
5992 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005993 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005994 }
5995
5996 {
5997 std::unique_lock<std::mutex> captureLock(captureMutex);
5998 syncFd = fd;
5999 captureResult = std::make_optional<status_t>(result);
6000 captureCondition.notify_one();
6001 }
6002 });
6003
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006004 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006005 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07006006 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006007 while (*captureResult == EAGAIN) {
6008 captureResult.reset();
6009 result = postMessageAsync(message);
6010 if (result != NO_ERROR) {
6011 return result;
6012 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07006013 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006014 }
6015 result = *captureResult;
6016 }
6017
6018 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006019 sync_wait(syncFd, -1);
6020 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006021 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00006022
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006023 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006024}
6025
chaviwa76b2712017-09-20 12:02:26 -07006026void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07006027 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006028 ANativeWindowBuffer* buffer, bool useIdentityTransform,
6029 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006030 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006031
chaviwa76b2712017-09-20 12:02:26 -07006032 const auto reqWidth = renderArea.getReqWidth();
6033 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006034 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006035 const auto transform = renderArea.getTransform();
6036 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006037
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006038 renderengine::DisplaySettings clientCompositionDisplay;
6039 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006040
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006041 // assume that bounds are never offset, and that they are the same as the
6042 // buffer bounds.
6043 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006044 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006045 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006046
6047 // Now take into account the rotation flag. We append a transform that
6048 // rotates the layer stack about the origin, then translate by buffer
6049 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006050 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006051 int displacementX = 0;
6052 int displacementY = 0;
6053 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6054 switch (rotation) {
6055 case ui::Transform::ROT_90:
6056 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006057 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006058 break;
6059 case ui::Transform::ROT_180:
6060 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006061 displacementY = renderArea.getBounds().getWidth();
6062 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006063 break;
6064 case ui::Transform::ROT_270:
6065 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006066 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006067 break;
6068 default:
6069 break;
6070 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006071
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006072 // We need to transform the clipping window into the right spot.
6073 // First, rotate the clipping rectangle by the rotation hint to get the
6074 // right orientation
6075 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6076 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6077 const vec4 rotClipTL = rotMatrix * clipTL;
6078 const vec4 rotClipBR = rotMatrix * clipBR;
6079 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6080 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6081 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6082 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6083
6084 // Now reposition the clipping rectangle with the displacement vector
6085 // computed above.
6086 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006087 clientCompositionDisplay.clip =
6088 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6089 newClipRight + displacementX, newClipBottom + displacementY);
6090
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006091 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006092 clientCompositionDisplay.globalTransform =
6093 clipTransform * clientCompositionDisplay.globalTransform;
6094
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006095 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6096 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006097
chaviw50da5042018-04-09 13:49:37 -07006098 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006099
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006100 renderengine::LayerSettings fillLayer;
6101 fillLayer.source.buffer.buffer = nullptr;
6102 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6103 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6104 fillLayer.alpha = half(alpha);
6105 clientCompositionLayers.push_back(fillLayer);
6106
6107 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006108 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006109 renderengine::LayerSettings layerSettings;
6110 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006111 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006112 if (prepared) {
6113 clientCompositionLayers.push_back(layerSettings);
6114 }
chaviwa76b2712017-09-20 12:02:26 -07006115 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006116
6117 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006118 // Use an empty fence for the buffer fence, since we just created the buffer so
6119 // there is no need for synchronization with the GPU.
6120 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006121 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006122 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006123 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006124 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006125
6126 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006127}
6128
chaviwa76b2712017-09-20 12:02:26 -07006129status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6130 TraverseLayersFunction traverseLayers,
6131 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006132 bool useIdentityTransform, bool forSystem,
6133 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006134 ATRACE_CALL();
6135
chaviwa76b2712017-09-20 12:02:26 -07006136 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006137 outCapturedSecureLayers =
6138 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006139 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006140
Robert Carr03480e22018-01-04 16:02:06 -08006141 // We allow the system server to take screenshots of secure layers for
6142 // use in situations like the Screen-rotation animation and place
6143 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006144 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006145 ALOGW("FB is protected: PERMISSION_DENIED");
6146 return PERMISSION_DENIED;
6147 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006148 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006149 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006150}
6151
chaviw95ef3c42019-02-14 10:55:09 -08006152void SurfaceFlinger::setInputWindowsFinished() {
6153 Mutex::Autolock _l(mStateLock);
6154
6155 mPendingSyncInputWindows = false;
6156 mTransactionCV.broadcast();
6157}
chaviw5f21a5e2019-02-14 10:00:34 -08006158
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006159// ---------------------------------------------------------------------------
6160
Dan Stoza412903f2017-04-27 13:42:17 -07006161void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6162 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006163}
6164
Dan Stoza412903f2017-04-27 13:42:17 -07006165void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6166 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006167}
6168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006169void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006170 const LayerVector::Visitor& visitor) {
6171 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006172 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006173 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006174 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006175 continue;
6176 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006177 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006178 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006179 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006180 return;
6181 }
chaviwa76b2712017-09-20 12:02:26 -07006182 if (!layer->isVisible()) {
6183 return;
6184 }
6185 visitor(layer);
6186 });
6187 }
6188}
6189
Dominik Laskowski22488f62019-03-28 09:53:04 -07006190void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6191 const std::vector<int32_t>& allowedConfigs) {
6192 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006193 return;
6194 }
6195
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006196 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
6197 allowedConfigs.end());
6198 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
6199 return;
6200 }
6201
Ady Abraham838de062019-02-04 10:24:03 -08006202 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006203 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
6204
6205 // TODO(b/140204874): This hack triggers a notification that something has changed, so
6206 // that listeners that care about a change in allowed configs can get the notification.
6207 // Giving current ActiveConfig so that most other listeners would just drop the event
6208 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
6209 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08006210
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006211 // Set the highest allowed config by iterating backwards on available refresh rates
Dominik Laskowski22488f62019-03-28 09:53:04 -07006212 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006213 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006214 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006215 ALOGV("switching to config %d", iter->second->configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006216 setDesiredActiveConfig(
6217 {iter->first, iter->second->configId, Scheduler::ConfigEvent::Changed});
Ady Abrahamde3b67b2019-03-25 16:38:10 -07006218 break;
Ady Abraham97d04232019-03-05 19:48:12 -08006219 }
6220 }
Ady Abraham838de062019-02-04 10:24:03 -08006221}
6222
Dominik Laskowski22488f62019-03-28 09:53:04 -07006223status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006224 const std::vector<int32_t>& allowedConfigs) {
6225 ATRACE_CALL();
6226
Dominik Laskowski22488f62019-03-28 09:53:04 -07006227 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006228 return BAD_VALUE;
6229 }
6230
Ady Abraham34392f72019-04-10 11:29:27 -07006231 if (mDebugDisplayConfigSetByBackdoor) {
6232 // ignore this request as config is overridden by backdoor
6233 return NO_ERROR;
6234 }
6235
Ady Abrahamabf91062019-10-18 14:17:23 -07006236 postMessageSync(new LambdaMessage([&]() {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006237 const auto display = getDisplayDeviceLocked(displayToken);
6238 if (!display) {
6239 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6240 displayToken.get());
6241 } else if (display->isVirtual()) {
6242 ALOGW("Attempt to set allowed display configs for virtual display");
6243 } else {
Ady Abrahamabf91062019-10-18 14:17:23 -07006244 Mutex::Autolock lock(mStateLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -07006245 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6246 }
Ady Abraham838de062019-02-04 10:24:03 -08006247 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006248
Ady Abraham838de062019-02-04 10:24:03 -08006249 return NO_ERROR;
6250}
6251
Dominik Laskowski22488f62019-03-28 09:53:04 -07006252status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006253 std::vector<int32_t>* outAllowedConfigs) {
6254 ATRACE_CALL();
6255
Dominik Laskowski22488f62019-03-28 09:53:04 -07006256 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006257 return BAD_VALUE;
6258 }
6259
Dominik Laskowski22488f62019-03-28 09:53:04 -07006260 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006261
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006262 const auto display = getDisplayDeviceLocked(displayToken);
6263 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006264 return NAME_NOT_FOUND;
6265 }
6266
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006267 if (display->isPrimary()) {
6268 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6269 }
6270
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006271 return NO_ERROR;
6272}
6273
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006274void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006275 mFlinger->setInputWindowsFinished();
6276}
6277
Robert Carrc0df3122019-04-11 13:18:21 -07006278sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6279 BBinder *b = handle->localBinder();
6280 if (b == nullptr) {
6281 return nullptr;
6282 }
6283 auto it = mLayersByLocalBinderToken.find(b);
6284 if (it != mLayersByLocalBinderToken.end()) {
6285 return it->second.promote();
6286 }
6287 return nullptr;
6288}
6289
Alec Mouri4545a8a2019-08-08 20:05:32 -07006290void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6291 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6292}
6293
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006294} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006295
Mathias Agopian3f844832013-08-07 21:24:32 -07006296#if defined(__gl_h_)
6297#error "don't include gl/gl.h in this file"
6298#endif
6299
6300#if defined(__gl2_h_)
6301#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006302#endif