blob: d91b0e7db785d01c6096b1341b288773033e8f8b [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
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800361 property_get("debug.sf.enable_hwc_vds", value, "0");
362 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800363 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800364
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800365 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800366 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800367 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700368
Yiwei Zhang243b3782018-05-15 17:40:04 -0700369 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700370 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
371 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
372
Ana Krulece5a06e02019-03-06 17:09:03 -0800373 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800374 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800375
376 int int_value = atoi(value);
377 if (int_value) {
378 mUseSmart90ForVideo = true;
379 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800380
Dan Stozaec460082018-12-17 15:35:09 -0800381 property_get("debug.sf.luma_sampling", value, "1");
382 mLumaSampling = atoi(value);
383
Ana Krulec757f63a2019-01-25 10:46:18 -0800384 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700385 mVsyncModulator.setPhaseOffsets(early, gl, late,
386 mPhaseOffsets->getOffsetThresholdForNextVsync());
Dan Stoza84d619e2018-03-28 17:07:36 -0700387
Romain Guy11d63f42017-07-20 12:47:14 -0700388 // We should be reading 'persist.sys.sf.color_saturation' here
389 // but since /data may be encrypted, we need to wait until after vold
390 // comes online to attempt to read the property. The property is
391 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800392
393 if (useTrebleTestingOverride()) {
394 // Without the override SurfaceFlinger cannot connect to HIDL
395 // services that are not listed in the manifests. Considered
396 // deriving the setting from the set service name, but it
397 // would be brittle if the name that's not 'default' is used
398 // for production purposes later on.
399 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
400 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401}
402
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403void SurfaceFlinger::onFirstRef()
404{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800405 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406}
407
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700408SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409
Dan Stozac7014012014-02-14 15:03:43 -0800410void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411{
412 // the window manager died on us. prepare its eulogy.
413
Andy McFadden13a082e2012-08-24 10:16:42 -0700414 // restore initial conditions (default device unblank, etc)
415 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416
417 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700418 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419}
420
Robert Carr1db73f62016-12-21 12:58:51 -0800421static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700422 status_t err = client->initCheck();
423 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425 }
Robert Carr1db73f62016-12-21 12:58:51 -0800426 return nullptr;
427}
428
429sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
430 return initClient(new Client(this));
431}
432
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700433sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
434 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435{
436 class DisplayToken : public BBinder {
437 sp<SurfaceFlinger> flinger;
438 virtual ~DisplayToken() {
439 // no more references, this display must be terminated
440 Mutex::Autolock _l(flinger->mStateLock);
441 flinger->mCurrentState.displays.removeItem(this);
442 flinger->setTransactionFlags(eDisplayTransactionNeeded);
443 }
444 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700445 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446 : flinger(flinger) {
447 }
448 };
449
450 sp<BBinder> token = new DisplayToken(this);
451
452 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 // Display ID is assigned when virtual display is allocated by HWC.
454 DisplayDeviceState state;
455 state.isSecure = secure;
456 state.displayName = displayName;
457 mCurrentState.displays.add(token, state);
458 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 return token;
460}
461
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700462void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700463 Mutex::Autolock _l(mStateLock);
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
466 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700467 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700468 return;
469 }
470
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
472 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700473 ALOGE("destroyDisplay called for non-virtual display");
474 return;
475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 mInterceptor->saveDisplayDeletion(state.sequenceId);
477 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 setTransactionFlags(eDisplayTransactionNeeded);
479}
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
482 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800484 const auto internalDisplayId = getInternalDisplayIdLocked();
485 if (!internalDisplayId) {
486 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 }
488
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800489 std::vector<PhysicalDisplayId> displayIds;
490 displayIds.reserve(mPhysicalDisplayTokens.size());
491 displayIds.push_back(internalDisplayId->value);
492
493 for (const auto& [id, token] : mPhysicalDisplayTokens) {
494 if (id != *internalDisplayId) {
495 displayIds.push_back(id.value);
496 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499 return displayIds;
500}
501
502sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
503 Mutex::Autolock lock(mStateLock);
504 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
Ady Abraham37965d42018-11-01 13:43:32 -0700507status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
508 if (!outGetColorManagement) {
509 return BAD_VALUE;
510 }
511 *outGetColorManagement = useColorManagement;
512 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700513}
514
Lloyd Pique441d5042018-10-18 16:49:51 -0700515HWComposer& SurfaceFlinger::getHwComposer() const {
516 return mCompositionEngine->getHwComposer();
517}
518
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700519renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
520 return mCompositionEngine->getRenderEngine();
521}
522
Lloyd Pique70d91362018-10-18 16:02:55 -0700523compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
524 return *mCompositionEngine.get();
525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700529 if (mStartPropertySetThread->join() != NO_ERROR) {
530 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800531 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800532 const nsecs_t now = systemTime();
533 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000534 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535
536 // wait patiently for the window manager death
537 const String16 name("window");
538 sp<IBinder> window(defaultServiceManager()->getService(name));
539 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700540 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 }
Robert Carr720e5062018-07-30 17:45:14 -0700542 sp<IBinder> input(defaultServiceManager()->getService(
543 String16("inputflinger")));
544 if (input == nullptr) {
545 ALOGE("Failed to link to input service");
546 } else {
547 mInputFlinger = interface_cast<IInputFlinger>(input);
548 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549
Steven Thomas050b2c82017-03-06 11:45:16 -0800550 if (mVrFlinger) {
551 mVrFlinger->OnBootFinished();
552 }
553
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700555 // formerly we would just kill the process, but we now ask it to exit so it
556 // can choose where to stop the animation.
557 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700558
559 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
560 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
561 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700562
Ana Krulecbd6654b2019-02-15 15:18:15 -0800563 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800564 readPersistentProperties();
565 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800566
Ady Abraham97d04232019-03-05 19:48:12 -0800567 // set the refresh rate according to the policy
Alec Mouri0a1cc962019-03-14 12:33:02 -0700568 const auto& performanceRefreshRate =
Dominik Laskowski22488f62019-03-28 09:53:04 -0700569 mRefreshRateConfigs.getRefreshRate(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800570
Dominik Laskowski22488f62019-03-28 09:53:04 -0700571 if (performanceRefreshRate && isDisplayConfigAllowed(performanceRefreshRate->configId)) {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800572 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800573 } else {
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800574 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800575 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800576 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800577}
578
Dan Stoza436ccf32018-06-21 12:10:12 -0700579uint32_t SurfaceFlinger::getNewTexture() {
580 {
581 std::lock_guard lock(mTexturePoolMutex);
582 if (!mTexturePool.empty()) {
583 uint32_t name = mTexturePool.back();
584 mTexturePool.pop_back();
585 ATRACE_INT("TexturePoolSize", mTexturePool.size());
586 return name;
587 }
588
589 // The pool was too small, so increase it for the future
590 ++mTexturePoolSize;
591 }
592
593 // The pool was empty, so we need to get a new texture name directly using a
594 // blocking call to the main thread
595 uint32_t name = 0;
596 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
597 return name;
598}
599
Mathias Agopian3f844832013-08-07 21:24:32 -0700600void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700601 std::lock_guard lock(mTexturePoolMutex);
602 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
603 // to actually delete this or not based on mTexturePoolSize
604 mTexturePool.push_back(texture);
605 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
613
Ana Krulec757f63a2019-01-25 10:46:18 -0800614 ALOGI("Phase offset NS: %" PRId64 "", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 // start the EventThread
Ana Krulecc2870422019-01-29 19:00:58 -0800618 mScheduler =
Ady Abraham09bd3922019-04-08 10:44:56 -0700619 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
620 mRefreshRateConfigs);
Ana Krulecc2870422019-01-29 19:00:58 -0800621 auto resyncCallback =
622 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800623
Ana Krulecc2870422019-01-29 19:00:58 -0800624 mAppConnectionHandle =
Ady Abraham45e4e362019-06-07 18:20:51 -0700625 mScheduler->createConnection("app", mVsyncModulator.getOffsets().app,
626 mPhaseOffsets->getOffsetThresholdForNextVsync(),
Ana Krulecc2870422019-01-29 19:00:58 -0800627 resyncCallback,
628 impl::EventThread::InterceptVSyncsCallback());
Ady Abraham45e4e362019-06-07 18:20:51 -0700629 mSfConnectionHandle =
630 mScheduler->createConnection("sf", mVsyncModulator.getOffsets().sf,
631 mPhaseOffsets->getOffsetThresholdForNextVsync(),
632 resyncCallback, [this](nsecs_t timestamp) {
633 mInterceptor->saveVSyncEvent(timestamp);
634 });
Ana Krulecc2870422019-01-29 19:00:58 -0800635
636 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
637 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
638 mSfConnectionHandle.get());
639
Kevin DuBois413287f2019-02-25 08:46:47 -0800640 mRegionSamplingThread =
641 new RegionSamplingThread(*this, *mScheduler,
642 RegionSamplingThread::EnvironmentTimingTunables());
643
Steven Thomasb02664d2017-07-26 18:48:28 -0700644 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700645 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700646 renderEngineFeature |= (useColorManagement ?
647 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700648 renderEngineFeature |= (useContextPriority ?
649 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700650 renderEngineFeature |=
651 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
652 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700653
654 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800655 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700656 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700657 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800658 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700659
660 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
661 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700662 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
663 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800664 // Process any initial hotplug and resulting display changes.
665 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700666 const auto display = getDefaultDisplayDeviceLocked();
667 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700668 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700669 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800670
Steven Thomas050b2c82017-03-06 11:45:16 -0800671 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700672 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700673 // This callback is called from the vr flinger dispatch thread. We
674 // need to call signalTransaction(), which requires holding
675 // mStateLock when we're not on the main thread. Acquiring
676 // mStateLock from the vr flinger dispatch thread might trigger a
677 // deadlock in surface flinger (see b/66916578), so post a message
678 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700679 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700680 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
681 mVrFlingerRequestsDisplay = requestDisplay;
682 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700683 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800684 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
686 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700687 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700688 .value_or(0),
689 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800690 if (!mVrFlinger) {
691 ALOGE("Failed to start vrflinger");
692 }
693 }
694
Mathias Agopian92a979a2012-08-02 18:32:23 -0700695 // initialize our drawing state
696 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700697
Andy McFadden13a082e2012-08-24 10:16:42 -0700698 // set initial conditions (e.g. unblank default device)
699 initializeDisplays();
700
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700701 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700702
Wei Wangf9b05ee2017-07-19 20:59:39 -0700703 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700704
705 const bool presentFenceReliable =
706 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
707 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700708
709 if (mStartPropertySetThread->Start() != NO_ERROR) {
710 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800711 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712
Alec Mouri93bc83d2019-04-17 14:47:43 -0700713 mScheduler->setChangeRefreshRateCallback(
714 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
715 Mutex::Autolock lock(mStateLock);
716 setRefreshRateTo(type, event);
717 });
Alec Mouri7f015182019-07-11 13:56:22 -0700718 mScheduler->setGetCurrentRefreshRateTypeCallback([this] {
719 Mutex::Autolock lock(mStateLock);
720 const auto display = getDefaultDisplayDeviceLocked();
721 if (!display) {
722 // If we don't have a default display the fallback to the default
723 // refresh rate type
724 return RefreshRateType::DEFAULT;
725 }
726
727 const int configId = display->getActiveConfig();
728 for (const auto& [type, refresh] : mRefreshRateConfigs.getRefreshRates()) {
729 if (refresh && refresh->configId == configId) {
730 return type;
731 }
732 }
733 // This should never happen, but just gracefully fallback to default.
734 return RefreshRateType::DEFAULT;
735 });
Alec Mouridc28b372019-04-18 21:17:13 -0700736 mScheduler->setGetVsyncPeriodCallback([this] {
737 Mutex::Autolock lock(mStateLock);
738 return getVsyncPeriod();
739 });
Ady Abraham09bd3922019-04-08 10:44:56 -0700740
Dominik Laskowski22488f62019-03-28 09:53:04 -0700741 mRefreshRateConfigs.populate(getHwComposer().getConfigs(*display->getId()));
742 mRefreshRateStats.setConfigMode(getHwComposer().getActiveConfigIndex(*display->getId()));
Ana Krulec7d1d6832018-12-27 11:10:09 -0800743
Dan Stoza9e56aa02015-11-02 13:00:03 -0800744 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700745}
746
Romain Guy11d63f42017-07-20 12:47:14 -0700747void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700748 Mutex::Autolock _l(mStateLock);
749
Romain Guy11d63f42017-07-20 12:47:14 -0700750 char value[PROPERTY_VALUE_MAX];
751
752 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800753 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700754 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800755 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100756
757 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700758 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800759
760 property_get("persist.sys.sf.color_mode", value, "0");
761 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700762}
763
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800765 // Start boot animation service by setting a property mailbox
766 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700767 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800768 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700769 if (mStartPropertySetThread->join() != NO_ERROR) {
770 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800771 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700775 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
Mathias Agopian875d8e12013-06-07 15:35:48 -0700778size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700779 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700780}
781
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800782// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800783
Jamie Gennis582270d2011-08-17 18:19:00 -0700784bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800785 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800786 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800787 return authenticateSurfaceTextureLocked(bufferProducer);
788}
789
790bool SurfaceFlinger::authenticateSurfaceTextureLocked(
791 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800792 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800793 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800794}
795
Brian Anderson6b376712017-04-04 10:51:39 -0700796status_t SurfaceFlinger::getSupportedFrameTimestamps(
797 std::vector<FrameEvent>* outSupported) const {
798 *outSupported = {
799 FrameEvent::REQUESTED_PRESENT,
800 FrameEvent::ACQUIRE,
801 FrameEvent::LATCH,
802 FrameEvent::FIRST_REFRESH_START,
803 FrameEvent::LAST_REFRESH_START,
804 FrameEvent::GPU_COMPOSITION_DONE,
805 FrameEvent::DEQUEUE_READY,
806 FrameEvent::RELEASE,
807 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700808 ConditionalLock _l(mStateLock,
809 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700810 if (!getHwComposer().hasCapability(
811 HWC2::Capability::PresentFenceIsNotReliable)) {
812 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
813 }
814 return NO_ERROR;
815}
816
Dominik Laskowski22488f62019-03-28 09:53:04 -0700817status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
818 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700819 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 return BAD_VALUE;
821 }
822
Dominik Laskowski22488f62019-03-28 09:53:04 -0700823 Mutex::Autolock lock(mStateLock);
824
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800825 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700826 if (!displayId) {
827 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700828 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 // TODO: Not sure if display density should handled by SF any longer
831 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700832 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700834 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800835 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700836 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700837 }
838 return density;
839 }
840 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700841 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700843 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700844 return getDensityFromProperty("ro.sf.lcd_density"); }
845 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700848
Dominik Laskowski075d3172018-05-24 15:50:06 -0700849 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700850 DisplayInfo info = DisplayInfo();
851
Dan Stoza9e56aa02015-11-02 13:00:03 -0800852 float xdpi = hwConfig->getDpiX();
853 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700854
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700855 info.w = hwConfig->getWidth();
856 info.h = hwConfig->getHeight();
857 // Default display viewport to display width and height
858 info.viewportW = info.w;
859 info.viewportH = info.h;
860
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800861 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700862 // The density of the device is provided by a build property
863 float density = Density::getBuildDensity() / 160.0f;
864 if (density == 0) {
865 // the build doesn't provide a density -- this is wrong!
866 // use xdpi instead
867 ALOGE("ro.sf.lcd_density must be defined as a build property");
868 density = xdpi / 160.0f;
869 }
870 if (Density::getEmuDensity()) {
871 // if "qemu.sf.lcd_density" is specified, it overrides everything
872 xdpi = ydpi = density = Density::getEmuDensity();
873 density /= 160.0f;
874 }
875 info.density = density;
876
877 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700878 const auto display = getDefaultDisplayDeviceLocked();
879 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700880
881 // This is for screenrecord
882 const Rect viewport = display->getViewport();
883 if (viewport.isValid()) {
884 info.viewportW = uint32_t(viewport.getWidth());
885 info.viewportH = uint32_t(viewport.getHeight());
886 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700887 } else {
888 // TODO: where should this value come from?
889 static const int TV_DENSITY = 213;
890 info.density = TV_DENSITY / 160.0f;
891 info.orientation = 0;
892 }
893
Dan Stoza7f7da322014-05-02 15:26:25 -0700894 info.xdpi = xdpi;
895 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham796beb02019-04-11 15:23:07 -0700897 const auto refreshRateType = mRefreshRateConfigs.getRefreshRateType(hwConfig->getId());
898 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
899 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800900
Andy McFadden91b2ca82014-06-13 14:04:23 -0700901 // This is how far in advance a buffer must be queued for
902 // presentation at a given time. If you want a buffer to appear
903 // on the screen at time N, you must submit the buffer before
904 // (N - presentationDeadline).
905 //
906 // Normally it's one full refresh period (to give SF a chance to
907 // latch the buffer), but this can be reduced by configuring a
908 // DispSync offset. Any additional delays introduced by the hardware
909 // composer or panel must be accounted for here.
910 //
911 // We add an additional 1ms to allow for processing time and
912 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700913 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700914
915 // All non-virtual displays are currently considered secure.
916 info.secure = true;
917
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800918 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700919 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800920 std::swap(info.w, info.h);
921 }
922
Michael Wright28f24d02016-07-12 13:30:53 -0700923 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700924 }
925
Dan Stoza7f7da322014-05-02 15:26:25 -0700926 return NO_ERROR;
927}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700928
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700929status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
930 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700931 return BAD_VALUE;
932 }
933
Ana Krulecc2870422019-01-29 19:00:58 -0800934 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700935 return NO_ERROR;
936}
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
939 const auto display = getDisplayDevice(displayToken);
940 if (!display) {
941 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800942 return BAD_VALUE;
943 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700946}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700947
Ady Abraham03b02dd2019-03-21 15:40:11 -0700948void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800950
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800952 // config twice. However event generation config might have changed so we need to update it
953 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800954 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700955 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
956 mDesiredActiveConfig = info;
957 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958
959 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800960 // This will trigger HWC refresh without resetting the idle timer.
961 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700962 // Start receiving vsync samples now, so that we can detect a period
963 // switch.
964 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700965 // As we called to set period, we will call to onRefreshRateChangeCompleted once
966 // DispSync model is locked.
967 mVsyncModulator.onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700968 mPhaseOffsets->setRefreshRateType(info.type);
969 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -0700970 mVsyncModulator.setPhaseOffsets(early, gl, late,
971 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 mDesiredActiveConfigChanged = true;
974 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700975
976 if (mRefreshRateOverlay) {
977 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
978 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979}
980
981status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
982 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800983
984 std::vector<int32_t> allowedConfig;
985 allowedConfig.push_back(mode);
986
987 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988}
989
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990void SurfaceFlinger::setActiveConfigInternal() {
991 ATRACE_CALL();
992
Dominik Laskowski22488f62019-03-28 09:53:04 -0700993 const auto display = getDefaultDisplayDeviceLocked();
994 if (!display) {
995 return;
996 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997
Dominik Laskowski22488f62019-03-28 09:53:04 -0700998 std::lock_guard<std::mutex> lock(mActiveConfigLock);
999 mRefreshRateStats.setConfigMode(mUpcomingActiveConfig.configId);
1000
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001001 display->setActiveConfig(mUpcomingActiveConfig.configId);
1002
Alec Mouri754c98a2019-03-18 18:53:42 -07001003 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001004 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001005 mVsyncModulator.setPhaseOffsets(early, gl, late,
1006 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001007 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001008
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001009 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -08001010 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
1011 mUpcomingActiveConfig.configId);
1012 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013}
1014
Ady Abraham53852a52019-05-28 18:07:44 -07001015void SurfaceFlinger::desiredActiveConfigChangeDone() {
1016 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1017 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1018 mDesiredActiveConfigChanged = false;
1019 ATRACE_INT("DesiredActiveConfigChanged", mDesiredActiveConfigChanged);
1020
1021 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
1022 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
1023 const auto [early, gl, late] = mPhaseOffsets->getCurrentOffsets();
Ady Abraham45e4e362019-06-07 18:20:51 -07001024 mVsyncModulator.setPhaseOffsets(early, gl, late,
1025 mPhaseOffsets->getOffsetThresholdForNextVsync());
Ady Abraham53852a52019-05-28 18:07:44 -07001026}
1027
Dominik Laskowski22488f62019-03-28 09:53:04 -07001028bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001029 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001031 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001033 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 return true;
1035 }
1036
1037 // We received the present fence from the HWC, so we assume it successfully updated
1038 // the config, hence we update SF.
1039 mCheckPendingFence = false;
1040 setActiveConfigInternal();
1041 }
1042
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001043 // Store the local variable to release the lock.
1044 ActiveConfigInfo desiredActiveConfig;
1045 {
1046 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001047 if (!mDesiredActiveConfigChanged) {
1048 return false;
1049 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001050 desiredActiveConfig = mDesiredActiveConfig;
1051 }
1052
Dominik Laskowski22488f62019-03-28 09:53:04 -07001053 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1055 // display is not valid or we are already in the requested mode
1056 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001057 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001059 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001060
Ady Abraham838de062019-02-04 10:24:03 -08001061 // Desired active config was set, it is different than the config currently in use, however
1062 // allowed configs might have change by the time we process the refresh.
1063 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001064 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001065 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001066 return false;
1067 }
Alec Mouri7f015182019-07-11 13:56:22 -07001068
Ady Abrahamb838aed2019-02-12 15:30:16 -08001069 mUpcomingActiveConfig = desiredActiveConfig;
1070 const auto displayId = display->getId();
1071 LOG_ALWAYS_FATAL_IF(!displayId);
1072
1073 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1074 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1075
1076 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001078 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001079 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001080}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1083 Vector<ColorMode>* outColorModes) {
1084 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001085 return BAD_VALUE;
1086 }
1087
Peiyong Lina52f0292018-03-14 17:26:31 -07001088 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001089 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001090 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001091 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1092
1093 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1094 if (!displayId) {
1095 return NAME_NOT_FOUND;
1096 }
1097
Dominik Laskowski075d3172018-05-24 15:50:06 -07001098 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001099 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001100 }
Michael Wright28f24d02016-07-12 13:30:53 -07001101 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001102
1103 // If it's built-in display and the configuration claims it's not wide color capable,
1104 // filter out all wide color modes. The typical reason why this happens is that the
1105 // hardware is not good enough to support GPU composition of wide color, and thus the
1106 // OEMs choose to disable this capability.
1107 if (isInternalDisplay && !hasWideColorDisplay) {
1108 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1109 isWideColorMode);
1110 } else {
1111 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1112 }
Michael Wright28f24d02016-07-12 13:30:53 -07001113
1114 return NO_ERROR;
1115}
1116
Daniel Solomon42d04562019-01-20 21:03:19 -08001117status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1118 ui::DisplayPrimaries &primaries) {
1119 if (!displayToken) {
1120 return BAD_VALUE;
1121 }
1122
1123 // Currently we only support this API for a single internal display.
1124 if (getInternalDisplayToken() != displayToken) {
1125 return BAD_VALUE;
1126 }
1127
1128 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1129 return NO_ERROR;
1130}
1131
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001132ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1133 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001134 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001135 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001136 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001137}
1138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001140 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001141 Vector<ColorMode> modes;
1142 getDisplayColorModes(displayToken, &modes);
1143 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1144 if (mode < ColorMode::NATIVE || !exists) {
1145 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1146 decodeColorMode(mode).c_str(), mode, displayToken.get());
1147 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001148 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001149 const auto display = getDisplayDevice(displayToken);
1150 if (!display) {
1151 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1152 decodeColorMode(mode).c_str(), mode, displayToken.get());
1153 } else if (display->isVirtual()) {
1154 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1155 decodeColorMode(mode).c_str(), mode);
1156 } else {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001157 display->getCompositionDisplay()->setColorMode(mode, Dataspace::UNKNOWN,
1158 RenderIntent::COLORIMETRIC);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159 }
1160 }));
1161
Michael Wright28f24d02016-07-12 13:30:53 -07001162 return NO_ERROR;
1163}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001164
Svetoslavd85084b2014-03-20 10:28:31 -07001165status_t SurfaceFlinger::clearAnimationFrameStats() {
1166 Mutex::Autolock _l(mStateLock);
1167 mAnimFrameTracker.clearStats();
1168 return NO_ERROR;
1169}
1170
1171status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1172 Mutex::Autolock _l(mStateLock);
1173 mAnimFrameTracker.getStats(outStats);
1174 return NO_ERROR;
1175}
1176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001177status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1178 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001179 Mutex::Autolock _l(mStateLock);
1180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001181 const auto display = getDisplayDeviceLocked(displayToken);
1182 if (!display) {
1183 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001184 return BAD_VALUE;
1185 }
1186
Peiyong Linfb069302018-04-25 14:34:31 -07001187 // At this point the DisplayDeivce should already be set up,
1188 // meaning the luminance information is already queried from
1189 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001190 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001191 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1192 capabilities.getDesiredMaxLuminance(),
1193 capabilities.getDesiredMaxAverageLuminance(),
1194 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001195
1196 return NO_ERROR;
1197}
1198
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001199status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1200 ui::PixelFormat* outFormat,
1201 ui::Dataspace* outDataspace,
1202 uint8_t* outComponentMask) const {
1203 if (!outFormat || !outDataspace || !outComponentMask) {
1204 return BAD_VALUE;
1205 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001206 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001207 if (!display || !display->getId()) {
1208 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1209 return BAD_VALUE;
1210 }
1211 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1212 outDataspace, outComponentMask);
1213}
1214
Kevin DuBois74e53772018-11-19 10:52:38 -08001215status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1216 bool enable, uint8_t componentMask,
1217 uint64_t maxFrames) const {
1218 const auto display = getDisplayDevice(displayToken);
1219 if (!display || !display->getId()) {
1220 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1221 return BAD_VALUE;
1222 }
1223
1224 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1225 componentMask, maxFrames);
1226}
1227
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001228status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1229 uint64_t maxFrames, uint64_t timestamp,
1230 DisplayedFrameStats* outStats) const {
1231 const auto display = getDisplayDevice(displayToken);
1232 if (!display || !display->getId()) {
1233 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1234 return BAD_VALUE;
1235 }
1236
1237 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1238 outStats);
1239}
1240
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001241status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1242 if (!outSupported) {
1243 return BAD_VALUE;
1244 }
1245 *outSupported = getRenderEngine().supportsProtectedContent();
1246 return NO_ERROR;
1247}
1248
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001249status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1250 bool* outIsWideColorDisplay) const {
1251 if (!displayToken || !outIsWideColorDisplay) {
1252 return BAD_VALUE;
1253 }
1254 Mutex::Autolock _l(mStateLock);
1255 const auto display = getDisplayDeviceLocked(displayToken);
1256 if (!display) {
1257 return BAD_VALUE;
1258 }
Peiyong Linff84a152019-05-17 18:36:19 -07001259
1260 // Use hasWideColorDisplay to override built-in display.
1261 const auto displayId = display->getId();
1262 if (displayId && displayId == getInternalDisplayIdLocked()) {
1263 *outIsWideColorDisplay = hasWideColorDisplay;
1264 return NO_ERROR;
1265 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001266 *outIsWideColorDisplay = display->hasWideColorGamut();
1267 return NO_ERROR;
1268}
1269
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001270status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001271 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001272 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001273
Chia-I Wu90f669f2017-10-05 14:24:41 -07001274 if (mInjectVSyncs == enable) {
1275 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001276 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001277
Ana Krulecc2870422019-01-29 19:00:58 -08001278 auto resyncCallback =
1279 mScheduler->makeResyncCallback(std::bind(&SurfaceFlinger::getVsyncPeriod, this));
Dominik Laskowskif654d572018-12-20 11:03:06 -08001280
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001281 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001282 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001283 if (enable) {
1284 ALOGV("VSync Injections enabled");
1285 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001286 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001287 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001288 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001289 impl::EventThread::InterceptVSyncsCallback(),
1290 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001291 }
Dominik Laskowskif654d572018-12-20 11:03:06 -08001292 mEventQueue->setEventThread(mInjectorEventThread.get(), std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001293 } else {
1294 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001295 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
1296 std::move(resyncCallback));
Chia-I Wu90f669f2017-10-05 14:24:41 -07001297 }
1298
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001299 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001300 }));
1301
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001302 return NO_ERROR;
1303}
1304
1305status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001306 Mutex::Autolock _l(mStateLock);
1307
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001308 if (!mInjectVSyncs) {
1309 ALOGE("VSync Injections not enabled");
1310 return BAD_VALUE;
1311 }
1312 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1313 ALOGV("Injecting VSync inside SurfaceFlinger");
1314 mVSyncInjector->onInjectSyncEvent(when);
1315 }
1316 return NO_ERROR;
1317}
1318
Lloyd Pique755e3192018-01-31 16:46:15 -08001319status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1320 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001321 // Try to acquire a lock for 1s, fail gracefully
1322 const status_t err = mStateLock.timedLock(s2ns(1));
1323 const bool locked = (err == NO_ERROR);
1324 if (!locked) {
1325 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1326 return TIMED_OUT;
1327 }
1328
1329 outLayers->clear();
1330 mCurrentState.traverseInZOrder([&](Layer* layer) {
1331 outLayers->push_back(layer->getLayerDebugInfo());
1332 });
1333
1334 mStateLock.unlock();
1335 return NO_ERROR;
1336}
1337
Peiyong Linc6780972018-10-28 15:24:08 -07001338status_t SurfaceFlinger::getCompositionPreference(
1339 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1340 Dataspace* outWideColorGamutDataspace,
1341 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001342 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001343 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001344 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001345 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001346 return NO_ERROR;
1347}
1348
Dan Stozaec460082018-12-17 15:35:09 -08001349status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1350 const sp<IBinder>& stopLayerHandle,
1351 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001352 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001353 return BAD_VALUE;
1354 }
1355 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001356 return NO_ERROR;
1357}
1358
Dan Stozaec460082018-12-17 15:35:09 -08001359status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001360 if (!listener) {
1361 return BAD_VALUE;
1362 }
Dan Stozaec460082018-12-17 15:35:09 -08001363 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001364 return NO_ERROR;
1365}
Dan Gittik57e63c52019-01-18 16:37:54 +00001366
1367status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1368 bool* outSupport) const {
1369 if (!displayToken || !outSupport) {
1370 return BAD_VALUE;
1371 }
1372 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1373 if (!displayId) {
1374 return NAME_NOT_FOUND;
1375 }
1376 *outSupport =
1377 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1378 return NO_ERROR;
1379}
1380
1381status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1382 float brightness) const {
1383 if (!displayToken) {
1384 return BAD_VALUE;
1385 }
1386 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1387 if (!displayId) {
1388 return NAME_NOT_FOUND;
1389 }
1390 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1391}
1392
Ady Abraham8532d012019-05-08 14:50:56 -07001393status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1394 PowerHint powerHint = static_cast<PowerHint>(hintId);
1395
1396 if (powerHint == PowerHint::INTERACTION) {
1397 mScheduler->notifyTouchEvent();
1398 }
1399
1400 return NO_ERROR;
1401}
1402
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001403// ----------------------------------------------------------------------------
1404
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001405sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001406 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001407 auto resyncCallback = mScheduler->makeResyncCallback([this] {
Dominik Laskowski83b88212018-12-11 13:34:06 -08001408 Mutex::Autolock lock(mStateLock);
1409 return getVsyncPeriod();
1410 });
Dominik Laskowskif654d572018-12-20 11:03:06 -08001411
Ana Krulecc2870422019-01-29 19:00:58 -08001412 const auto& handle =
1413 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001414
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001415 return mScheduler->createDisplayEventConnection(handle, std::move(resyncCallback),
1416 configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001417}
1418
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001419// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001420
1421void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001422 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001423}
1424
1425void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001426 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001427 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001428}
1429
1430void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001431 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001432 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001433}
1434
1435void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001436 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001437 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001438}
1439
1440status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001441 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001442 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001443}
1444
1445status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001446 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001447 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001448 if (res == NO_ERROR) {
1449 msg->wait();
1450 }
1451 return res;
1452}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001453
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001454void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001455 do {
1456 waitForEvent();
1457 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001458}
1459
Dominik Laskowski83b88212018-12-11 13:34:06 -08001460nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001461 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001462 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1463 return 0;
1464 }
1465
1466 const auto config = getHwComposer().getActiveConfig(*displayId);
1467 return config ? config->getVsyncPeriod() : 0;
1468}
1469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1471 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001472 ATRACE_NAME("SF onVsync");
1473
Steven Thomas3cfac282017-02-06 12:29:30 -08001474 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001476 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 return;
1478 }
1479
Dominik Laskowski075d3172018-05-24 15:50:06 -07001480 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001481 return;
1482 }
1483
Dominik Laskowski075d3172018-05-24 15:50:06 -07001484 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001485 // For now, we don't do anything with external display vsyncs.
1486 return;
1487 }
1488
Alec Mourif8e689c2019-05-20 18:32:22 -07001489 bool periodFlushed = false;
1490 mScheduler->addResyncSample(timestamp, &periodFlushed);
1491 if (periodFlushed) {
1492 mVsyncModulator.onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001493 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001494}
1495
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001496void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001497 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1498 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499}
1500
Dominik Laskowski22488f62019-03-28 09:53:04 -07001501bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) {
1502 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001503}
1504
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001505void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001506 const auto display = getDefaultDisplayDeviceLocked();
1507 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001508 return;
1509 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001510 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001511
Ana Krulec7d1d6832018-12-27 11:10:09 -08001512 // Don't do any updating if the current fps is the same as the new one.
Dominik Laskowski22488f62019-03-28 09:53:04 -07001513 const auto& refreshRateConfig = mRefreshRateConfigs.getRefreshRate(refreshRate);
Alec Mouri0a1cc962019-03-14 12:33:02 -07001514 if (!refreshRateConfig) {
1515 ALOGV("Skipping refresh rate change request for unsupported rate.");
Ady Abraham1902d072019-03-01 17:18:59 -08001516 return;
Ana Krulec7d1d6832018-12-27 11:10:09 -08001517 }
Ady Abraham1902d072019-03-01 17:18:59 -08001518
Alec Mouri0a1cc962019-03-14 12:33:02 -07001519 const int desiredConfigId = refreshRateConfig->configId;
1520
Dominik Laskowski22488f62019-03-28 09:53:04 -07001521 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001522 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1523 return;
1524 }
1525
Dominik Laskowski22488f62019-03-28 09:53:04 -07001526 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001527}
1528
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001529void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001530 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001531 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001532 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001533
Lloyd Piqueba04e622017-12-14 17:11:26 -08001534 // Ignore events that do not have the right sequenceId.
1535 if (sequenceId != getBE().mComposerSequenceId) {
1536 return;
1537 }
1538
Steven Thomasb02664d2017-07-26 18:48:28 -07001539 // Only lock if we're not on the main thread. This function is normally
1540 // called on a hwbinder thread, but for the primary display it's called on
1541 // the main thread with the state lock already held, so don't attempt to
1542 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001543 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001544
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001545 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001546
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001547 if (std::this_thread::get_id() == mMainThreadId) {
1548 // Process all pending hot plug events immediately if we are on the main thread.
1549 processDisplayHotplugEventsLocked();
1550 }
1551
Lloyd Piqueba04e622017-12-14 17:11:26 -08001552 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001553}
1554
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001555void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001556 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001557 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001559 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001560 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001561}
1562
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001563void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001564 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001565
1566 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1567 // display power state.
1568 postMessageAsync(new LambdaMessage(
1569 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1570}
1571
1572void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1573 ATRACE_CALL();
1574
Ady Abraham27c70212019-06-11 10:52:26 -07001575 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1576
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001577 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001578 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1579 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001580 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001581 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001582 }
Mathias Agopian86303202012-07-24 22:46:10 -07001583}
1584
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001585// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001586void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001587 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001588 // Clear the drawing state so that the logic inside of
1589 // handleTransactionLocked will fire. It will determine the delta between
1590 // mCurrentState and mDrawingState and re-apply all changes when we make the
1591 // transition.
1592 mDrawingState.displays.clear();
1593 mDisplays.clear();
1594}
1595
Steven Thomas050b2c82017-03-06 11:45:16 -08001596void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001597 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001598 if (!mVrFlinger)
1599 return;
1600 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001601 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001602 return;
1603 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001604
Lloyd Pique441d5042018-10-18 16:49:51 -07001605 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001606 ALOGE("Vr flinger is only supported for remote hardware composer"
1607 " service connections. Ignoring request to transition to vr"
1608 " flinger.");
1609 mVrFlingerRequestsDisplay = false;
1610 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001611 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001612
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001613 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001614
Steven Thomas0123ac62018-07-12 11:32:34 -07001615 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001616 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001617
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001618 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001619
1620 // Clear out all the output layers from the composition engine for all
1621 // displays before destroying the hardware composer interface. This ensures
1622 // any HWC layers are destroyed through that interface before it becomes
1623 // invalid.
1624 for (const auto& [token, displayDevice] : mDisplays) {
1625 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1626 compositionengine::Output::OutputLayers());
1627 }
1628
Steven Thomas0123ac62018-07-12 11:32:34 -07001629 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1630 // called below. Clear the reference now so we don't accidentally use it
1631 // later.
1632 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001633
Steven Thomasb02664d2017-07-26 18:48:28 -07001634 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001635 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001636 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001637
Steven Thomasb02664d2017-07-26 18:48:28 -07001638 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001639 // Delete the current instance before creating the new one
1640 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1641 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1642 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1643 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001644
Lloyd Pique441d5042018-10-18 16:49:51 -07001645 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001646 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001647
1648 if (vrFlingerRequestsDisplay) {
1649 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001651
1652 mVisibleRegionsDirty = true;
1653 invalidateHwcGeometry();
1654
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001655 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001656 display = getDefaultDisplayDeviceLocked();
1657 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001658 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001659
Steven Thomasb02664d2017-07-26 18:48:28 -07001660 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001661 const nsecs_t vsyncPeriod = getVsyncPeriod();
1662 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001663
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001664 // The present fences returned from vr_hwc are not an accurate
1665 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001666 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001667
Steven Thomasb02664d2017-07-26 18:48:28 -07001668 // Use phase of 0 since phase is not known.
1669 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001670 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001671 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001672
Ana Krulecc2870422019-01-29 19:00:58 -08001673 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001674
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001675 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001676 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001677}
1678
Ady Abrahambe0f9482019-04-24 15:41:53 -07001679bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1680 // We are storing the last 2 present fences. If sf's phase offset is to be
1681 // woken up before the actual vsync but targeting the next vsync, we need to check
1682 // fence N-2
1683 const sp<Fence>& fence =
1684 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1685 ? mPreviousPresentFences[0]
1686 : mPreviousPresentFences[1];
1687
1688 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1689}
1690
Ady Abraham7c03ce62019-07-19 10:59:45 -07001691void SurfaceFlinger::populateExpectedPresentTime() NO_THREAD_SAFETY_ANALYSIS {
Alec Mouriaa614192019-06-06 13:28:34 -07001692 DisplayStatInfo stats;
1693 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001694 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001695 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham7c03ce62019-07-19 10:59:45 -07001696 mExpectedPresentTime =
Alec Mouriaa614192019-06-06 13:28:34 -07001697 mVsyncModulator.getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
1698 ? presentTime
1699 : presentTime + stats.vsyncPeriod;
Alec Mouriaa614192019-06-06 13:28:34 -07001700}
1701
Dominik Laskowski22488f62019-03-28 09:53:04 -07001702void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001703 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001704 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001705 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001706 // calculate the expected present time once and use the cached
1707 // value throughout this frame to make sure all layers are
1708 // seeing this same value.
1709 populateExpectedPresentTime();
1710
Ady Abrahambe0f9482019-04-24 15:41:53 -07001711 bool frameMissed = previousFrameMissed();
Alec Mouricc0fc602019-02-26 21:45:19 -08001712 bool hwcFrameMissed = mHadDeviceComposition && frameMissed;
1713 bool gpuFrameMissed = mHadClientComposition && frameMissed;
1714 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
1715 ATRACE_INT("HwcFrameMissed", static_cast<int>(hwcFrameMissed));
1716 ATRACE_INT("GpuFrameMissed", static_cast<int>(gpuFrameMissed));
1717 if (frameMissed) {
1718 mFrameMissedCount++;
1719 mTimeStats->incrementMissedFrames();
1720 }
1721
Alec Mouri40189b02019-03-05 15:07:54 -08001722 if (hwcFrameMissed) {
1723 mHwcFrameMissedCount++;
1724 }
1725
1726 if (gpuFrameMissed) {
1727 mGpuFrameMissedCount++;
1728 }
1729
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001730 if (mUseSmart90ForVideo) {
1731 // This call is made each time SF wakes up and creates a new frame. It is part
1732 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001733 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001734 }
1735
Ady Abrahamb838aed2019-02-12 15:30:16 -08001736 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001737 break;
1738 }
1739
Pete Bentleycc1ce642019-09-12 11:36:29 +00001740 // For now, only propagate backpressure when missing a hwc frame.
1741 if (hwcFrameMissed && !gpuFrameMissed) {
1742 if (mPropagateBackpressure) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001743 signalLayerUpdate();
1744 break;
1745 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001746 }
Dan Stoza50182882016-07-08 12:02:20 -07001747
Steven Thomas050b2c82017-03-06 11:45:16 -08001748 // Now that we're going to make it to the handleMessageTransaction()
1749 // call below it's safe to call updateVrFlinger(), which will
1750 // potentially trigger a display handoff.
1751 updateVrFlinger();
1752
Dan Stoza6b9454d2014-11-07 16:00:59 -08001753 bool refreshNeeded = handleMessageTransaction();
1754 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001755
1756 updateCursorAsync();
1757 updateInputFlinger();
1758
Dan Stoza58784442014-12-02 16:58:17 -08001759 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001760 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001761 // Signal a refresh if a transaction modified the window state,
1762 // a new buffer was latched, or if HWC has requested a full
1763 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001764 signalRefresh();
1765 }
1766 break;
1767 }
1768 case MessageQueue::REFRESH: {
1769 handleMessageRefresh();
1770 break;
1771 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001772 }
1773}
1774
Dan Stoza6b9454d2014-11-07 16:00:59 -08001775bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001776 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001777 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001778
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001779 bool flushedATransaction = flushTransactionQueues();
1780
1781 bool runHandleTransaction = transactionFlags &&
1782 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1783
1784 if (runHandleTransaction) {
1785 handleTransaction(eTransactionMask);
1786 } else {
1787 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001788 }
1789
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001790 if (transactionFlushNeeded()) {
1791 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001792 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001793
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001794 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001795}
1796
Mathias Agopian4fec8732012-06-29 14:12:52 -07001797void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001798 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001799
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001800 mRefreshPending = false;
1801
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001802 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001803 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001804 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001805 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001806 for (const auto& [token, display] : mDisplays) {
1807 beginFrame(display);
1808 prepareFrame(display);
1809 doDebugFlashRegions(display, repaintEverything);
1810 doComposition(display, repaintEverything);
1811 }
1812
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001813 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001814
1815 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001816 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001817
Dan Stozabfbffeb2016-07-21 14:49:33 -07001818 mHadClientComposition = false;
Alec Mouricc0fc602019-02-26 21:45:19 -08001819 mHadDeviceComposition = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001820 for (const auto& [token, displayDevice] : mDisplays) {
1821 auto display = displayDevice->getCompositionDisplay();
1822 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07001823 mHadClientComposition =
Lloyd Pique32cbe282018-10-19 13:09:22 -07001824 mHadClientComposition || getHwComposer().hasClientComposition(displayId);
Alec Mouricc0fc602019-02-26 21:45:19 -08001825 mHadDeviceComposition =
1826 mHadDeviceComposition || getHwComposer().hasDeviceComposition(displayId);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001827 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001828
Jorim Jaggi90535212018-05-23 23:44:06 +02001829 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001830
David Sodman7e4ae112018-02-09 15:02:28 -08001831 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001832}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001833
David Sodmanfa9b2af2017-12-24 13:28:59 -08001834
1835bool SurfaceFlinger::handleMessageInvalidate() {
1836 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001837 bool refreshNeeded = handlePageFlip();
1838
Vishnu Nair4351ad52019-02-11 14:13:02 -08001839 if (mVisibleRegionsDirty) {
1840 computeLayerBounds();
Nataniel Borges2b796da2019-02-15 13:32:18 -08001841 if (mTracingEnabled) {
1842 mTracing.notify("visibleRegionsDirty");
1843 }
Vishnu Nair4351ad52019-02-11 14:13:02 -08001844 }
1845
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001846 for (auto& layer : mLayersPendingRefresh) {
1847 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001848 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001849 invalidateLayerStack(layer, visibleReg);
1850 }
1851 mLayersPendingRefresh.clear();
1852 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001853}
1854
David Sodman79bba0e2018-08-05 18:07:49 -07001855void SurfaceFlinger::calculateWorkingSet() {
1856 ATRACE_CALL();
1857 ALOGV(__FUNCTION__);
1858
David Sodman79bba0e2018-08-05 18:07:49 -07001859 // build the h/w work list
1860 if (CC_UNLIKELY(mGeometryInvalid)) {
1861 mGeometryInvalid = false;
Lloyd Pique32cbe282018-10-19 13:09:22 -07001862 for (const auto& [token, displayDevice] : mDisplays) {
1863 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001864
Lloyd Piquea83776c2019-01-29 18:42:32 -08001865 uint32_t zOrder = 0;
David Sodman79bba0e2018-08-05 18:07:49 -07001866
Lloyd Piquea83776c2019-01-29 18:42:32 -08001867 for (auto& layer : display->getOutputLayersOrderedByZ()) {
1868 auto& compositionState = layer->editState();
1869 compositionState.forceClientComposition = false;
1870 if (!compositionState.hwc || mDebugDisableHWC || mDebugRegion) {
1871 compositionState.forceClientComposition = true;
David Sodman79bba0e2018-08-05 18:07:49 -07001872 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001873
Lloyd Piquea83776c2019-01-29 18:42:32 -08001874 // The output Z order is set here based on a simple counter.
1875 compositionState.z = zOrder++;
1876
1877 // Update the display independent composition state. This goes
1878 // to the general composition layer state structure.
1879 // TODO: Do this once per compositionengine::CompositionLayer.
1880 layer->getLayerFE().latchCompositionState(layer->getLayer().editState().frontEnd,
1881 true);
1882
1883 // Recalculate the geometry state of the output layer.
1884 layer->updateCompositionState(true);
1885
1886 // Write the updated geometry state to the HWC
1887 layer->writeStateToHWC(true);
David Sodman79bba0e2018-08-05 18:07:49 -07001888 }
1889 }
1890 }
1891
1892 // Set the per-frame data
Lloyd Pique32cbe282018-10-19 13:09:22 -07001893 for (const auto& [token, displayDevice] : mDisplays) {
1894 auto display = displayDevice->getCompositionDisplay();
David Sodman79bba0e2018-08-05 18:07:49 -07001895 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001896 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001897 continue;
1898 }
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001899 auto* profile = display->getDisplayColorProfile();
David Sodman79bba0e2018-08-05 18:07:49 -07001900
1901 if (mDrawingState.colorMatrixChanged) {
1902 display->setColorTransform(mDrawingState.colorMatrix);
David Sodman79bba0e2018-08-05 18:07:49 -07001903 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001904 Dataspace targetDataspace = Dataspace::UNKNOWN;
1905 if (useColorManagement) {
1906 ColorMode colorMode;
1907 RenderIntent renderIntent;
1908 pickColorMode(displayDevice, &colorMode, &targetDataspace, &renderIntent);
1909 display->setColorMode(colorMode, targetDataspace, renderIntent);
Yichi Chenda901bf2019-06-28 14:58:27 +08001910
1911 if (isHdrColorMode(colorMode)) {
1912 targetDataspace = Dataspace::UNKNOWN;
1913 } else if (mColorSpaceAgnosticDataspace != Dataspace::UNKNOWN) {
1914 targetDataspace = mColorSpaceAgnosticDataspace;
1915 }
Peiyong Linc502cb72019-03-01 15:00:23 -08001916 }
Yichi Chenda901bf2019-06-28 14:58:27 +08001917
Lloyd Pique32cbe282018-10-19 13:09:22 -07001918 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
David Sodman79bba0e2018-08-05 18:07:49 -07001919 if (layer->isHdrY410()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001920 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001921 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1922 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001923 !profile->hasHDR10Support()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001924 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001925 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1926 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07001927 !profile->hasHLGSupport()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001928 layer->forceClientComposition(displayDevice);
David Sodman79bba0e2018-08-05 18:07:49 -07001929 }
1930
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001931 if (layer->getRoundedCornerState().radius > 0.0f) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001932 layer->forceClientComposition(displayDevice);
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001933 }
1934
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001935 if (layer->getForceClientComposition(displayDevice)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001936 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001937 layer->setCompositionType(displayDevice,
1938 Hwc2::IComposerClient::Composition::CLIENT);
David Sodman79bba0e2018-08-05 18:07:49 -07001939 continue;
1940 }
1941
Lloyd Pique32cbe282018-10-19 13:09:22 -07001942 const auto& displayState = display->getState();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001943 layer->setPerFrameData(displayDevice, displayState.transform, displayState.viewport,
Yichi Chenda901bf2019-06-28 14:58:27 +08001944 displayDevice->getSupportedPerFrameMetadata(), targetDataspace);
David Sodman79bba0e2018-08-05 18:07:49 -07001945 }
1946 }
1947
1948 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001949
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001950 for (const auto& [token, displayDevice] : mDisplays) {
1951 auto display = displayDevice->getCompositionDisplay();
1952 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Lloyd Pique0b785d82018-12-04 17:25:27 -08001953 auto& layerState = layer->getCompositionLayer()->editState().frontEnd;
1954 layerState.compositionType = static_cast<Hwc2::IComposerClient::Composition>(
1955 layer->getCompositionType(displayDevice));
David Sodmanba340492018-08-05 21:51:33 -07001956 }
1957 }
David Sodman79bba0e2018-08-05 18:07:49 -07001958}
1959
Lloyd Pique32cbe282018-10-19 13:09:22 -07001960void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& displayDevice,
1961 bool repaintEverything) {
1962 auto display = displayDevice->getCompositionDisplay();
1963 const auto& displayState = display->getState();
1964
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965 // is debugging enabled
1966 if (CC_LIKELY(!mDebugRegion))
1967 return;
1968
Lloyd Pique32cbe282018-10-19 13:09:22 -07001969 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08001970 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001971 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
David Sodmanfa9b2af2017-12-24 13:28:59 -08001972 if (!dirtyRegion.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001973 base::unique_fd readyFence;
David Sodmanfa9b2af2017-12-24 13:28:59 -08001974 // redraw the whole screen
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001975 doComposeSurfaces(displayDevice, dirtyRegion, &readyFence);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001976
Alec Mourie7d1d4a2019-02-05 01:13:46 +00001977 display->getRenderSurface()->queueBuffer(std::move(readyFence));
Mathias Agopiancd60f992012-08-16 16:28:27 -07001978 }
1979 }
1980
Lloyd Pique32cbe282018-10-19 13:09:22 -07001981 postFramebuffer(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001982
1983 if (mDebugRegion > 1) {
1984 usleep(mDebugRegion * 1000);
1985 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001986
Lloyd Pique32cbe282018-10-19 13:09:22 -07001987 prepareFrame(displayDevice);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001988}
1989
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001990void SurfaceFlinger::logLayerStats() {
1991 ATRACE_CALL();
1992 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001993 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001994 if (display->isPrimary()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08001995 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001996 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001997 }
1998 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001999
2000 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08002001 }
2002}
2003
David Sodman2b406362017-12-15 13:33:47 -08002004void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 ATRACE_CALL();
2007 ALOGV("preComposition");
2008
David Sodman2b406362017-12-15 13:33:47 -08002009 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
2010
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08002012 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08002013 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002014 needExtraInvalidate = true;
2015 }
Robert Carr2047fae2016-11-28 14:09:09 -08002016 });
2017
Mathias Agopiancd60f992012-08-16 16:28:27 -07002018 if (needExtraInvalidate) {
2019 signalLayerUpdate();
2020 }
2021}
2022
Ana Krulece588e312018-09-18 12:32:24 -07002023void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2024 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002025 // Update queue of past composite+present times and determine the
2026 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002027 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002028 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002029 while (!getBE().mCompositePresentTimes.empty()) {
2030 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002031 // Cached values should have been updated before calling this method,
2032 // which helps avoid duplicate syscalls.
2033 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2034 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2035 break;
2036 }
2037 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002038 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002039 }
2040
2041 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002042 while (getBE().mCompositePresentTimes.size() > 16) {
2043 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002044 }
2045
Ana Krulece588e312018-09-18 12:32:24 -07002046 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002047}
2048
Ana Krulece588e312018-09-18 12:32:24 -07002049void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2050 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002051 // Integer division and modulo round toward 0 not -inf, so we need to
2052 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08002053 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
2054 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
2055 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002056
Ana Krulec757f63a2019-01-25 10:46:18 -08002057 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002058 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002059 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002060 }
2061
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002062 // Snap the latency to a value that removes scheduling jitter from the
2063 // composition and present times, which often have >1ms of jitter.
2064 // Reducing jitter is important if an app attempts to extrapolate
2065 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08002066 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002067 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002068 nsecs_t bias = stats.vsyncPeriod / 2;
2069 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2070 nsecs_t snappedCompositeToPresentLatency =
2071 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002072
David Sodman99974d22017-11-28 12:04:33 -08002073 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002074 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2075 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002076 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077}
2078
David Sodman2b406362017-12-15 13:33:47 -08002079void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002080{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002081 ATRACE_CALL();
2082 ALOGV("postComposition");
2083
Brian Anderson3546a3f2016-07-14 11:51:14 -07002084 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002085 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002086 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002087 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002088 }
2089
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002090 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002091 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002092
David Sodman73beded2017-11-15 11:56:06 -08002093 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002094 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002095 if (displayDevice && getHwComposer().hasClientComposition(displayDevice->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002096 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002097 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2098 ->getRenderSurface()
2099 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002100 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002101 } else {
2102 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2103 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002104
David Sodman73beded2017-11-15 11:56:06 -08002105 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002106 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2107 mPreviousPresentFences[0] = displayDevice
2108 ? getHwComposer().getPresentFence(*displayDevice->getId())
2109 : Fence::NO_FENCE;
2110 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002111 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002112
Ana Krulece588e312018-09-18 12:32:24 -07002113 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002114 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002115
David Sodman2b406362017-12-15 13:33:47 -08002116 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002117 // when we started doing work for this frame, but that should be okay
2118 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07002119 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002120 CompositorTiming compositorTiming;
2121 {
David Sodman99974d22017-11-28 12:04:33 -08002122 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2123 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002124 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002125
Robert Carr2047fae2016-11-28 14:09:09 -08002126 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002127 bool frameLatched =
2128 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
2129 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002130 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08002131 recordBufferingStats(layer->getName().string(),
2132 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002133 }
Robert Carr2047fae2016-11-28 14:09:09 -08002134 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002135
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002136 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002137 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002138 }
2139
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002140 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002141 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2142 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002143 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002144 }
2145 }
2146
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002147 if (mAnimCompositionPending) {
2148 mAnimCompositionPending = false;
2149
Brian Anderson4e606e32017-03-16 15:34:57 -07002150 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002151 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002152 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002153 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002154 // The HWC doesn't support present fences, so use the refresh
2155 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002156 const nsecs_t presentTime =
2157 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002158 mAnimFrameTracker.setActualPresentTime(presentTime);
2159 }
2160 mAnimFrameTracker.advanceFrame();
2161 }
Dan Stozab90cf072015-03-05 11:05:59 -08002162
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002163 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002164 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002165 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002166 }
2167
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002168 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002169
Lloyd Pique32cbe282018-10-19 13:09:22 -07002170 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2171 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002172 return;
2173 }
2174
2175 nsecs_t currentTime = systemTime();
2176 if (mHasPoweredOff) {
2177 mHasPoweredOff = false;
2178 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002179 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002180 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002181 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2182 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002183 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002184 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002185 }
David Sodman4a36e932017-11-07 14:29:47 -08002186 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002187 }
David Sodman4a36e932017-11-07 14:29:47 -08002188 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002189
2190 {
2191 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002192 if (mTexturePool.size() < mTexturePoolSize) {
2193 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002194 const size_t offset = mTexturePool.size();
2195 mTexturePool.resize(mTexturePoolSize);
2196 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2197 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002198 } else if (mTexturePool.size() > mTexturePoolSize) {
2199 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2200 const size_t offset = mTexturePoolSize;
2201 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2202 mTexturePool.resize(mTexturePoolSize);
2203 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002204 }
2205 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002206
Ady Abrahambe0f9482019-04-24 15:41:53 -07002207 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallf384e052019-06-12 13:25:07 -07002208
2209 // Lock the mStateLock in case SurfaceFlinger is in the middle of applying a transaction.
2210 // If we do not lock here, a callback could be sent without all of its SurfaceControls and
2211 // metrics.
2212 {
2213 Mutex::Autolock _l(mStateLock);
2214 mTransactionCompletedThread.sendCallbacks();
2215 }
Ady Abraham8164d482019-01-11 14:47:59 -08002216
Kevin DuBois413287f2019-02-25 08:46:47 -08002217 if (mLumaSampling && mRegionSamplingThread) {
2218 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002219 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002220
2221 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2222 // side-effect of getTotalSize(), so we check that again here
2223 if (ATRACE_ENABLED()) {
2224 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2225 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002226}
2227
Vishnu Nair4351ad52019-02-11 14:13:02 -08002228void SurfaceFlinger::computeLayerBounds() {
2229 for (const auto& pair : mDisplays) {
2230 const auto& displayDevice = pair.second;
2231 const auto display = displayDevice->getCompositionDisplay();
2232 for (const auto& layer : mDrawingState.layersSortedByZ) {
2233 // only consider the layers on the given layer stack
2234 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002235 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002236 }
2237
2238 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2239 }
2240 }
2241}
2242
Mathias Agopiancd60f992012-08-16 16:28:27 -07002243void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002244 ATRACE_CALL();
2245 ALOGV("rebuildLayerStacks");
2246
Mathias Agopiancd60f992012-08-16 16:28:27 -07002247 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002248 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002249 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002250 mVisibleRegionsDirty = false;
2251 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002252
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002253 for (const auto& pair : mDisplays) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002254 const auto& displayDevice = pair.second;
2255 auto display = displayDevice->getCompositionDisplay();
2256 const auto& displayState = display->getState();
Jeff Sharkey76488112017-02-27 14:15:18 -07002257 Region opaqueRegion;
2258 Region dirtyRegion;
Lloyd Piquecc01a452018-12-04 17:24:00 -08002259 compositionengine::Output::OutputLayers layersSortedByZ;
2260 Vector<sp<Layer>> deprecated_layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002261 Vector<sp<Layer>> layersNeedingFences;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002262 const ui::Transform& tr = displayState.transform;
2263 const Rect bounds = displayState.bounds;
2264 if (displayState.isEnabled) {
2265 computeVisibleRegions(displayDevice, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002266
Jeff Sharkey76488112017-02-27 14:15:18 -07002267 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquecc01a452018-12-04 17:24:00 -08002268 auto compositionLayer = layer->getCompositionLayer();
2269 if (compositionLayer == nullptr) {
2270 return;
2271 }
2272
Lloyd Pique32cbe282018-10-19 13:09:22 -07002273 const auto displayId = displayDevice->getId();
Lloyd Piquecc01a452018-12-04 17:24:00 -08002274 sp<compositionengine::LayerFE> layerFE = compositionLayer->getLayerFE();
2275 LOG_ALWAYS_FATAL_IF(layerFE.get() == nullptr);
2276
Lloyd Pique07e33212018-12-18 16:33:37 -08002277 bool needsOutputLayer = false;
2278
Lloyd Piqueef36b002019-01-23 17:52:04 -08002279 if (display->belongsInOutput(layer->getLayerStack(),
2280 layer->getPrimaryDisplayOnly())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002281 Region drawRegion(tr.transform(
2282 layer->visibleNonTransparentRegion));
2283 drawRegion.andSelf(bounds);
2284 if (!drawRegion.isEmpty()) {
Lloyd Pique07e33212018-12-18 16:33:37 -08002285 needsOutputLayer = true;
Jeff Sharkey76488112017-02-27 14:15:18 -07002286 }
Chia-I Wu83806892017-11-16 10:50:20 -08002287 }
2288
Lloyd Pique07e33212018-12-18 16:33:37 -08002289 if (needsOutputLayer) {
2290 layersSortedByZ.emplace_back(
2291 display->getOrCreateOutputLayer(displayId, compositionLayer,
2292 layerFE));
2293 deprecated_layersSortedByZ.add(layer);
2294
2295 auto& outputLayerState = layersSortedByZ.back()->editState();
2296 outputLayerState.visibleRegion =
2297 tr.transform(layer->visibleRegion.intersect(displayState.viewport));
2298 } else if (displayId) {
2299 // For layers that are being removed from a HWC display,
2300 // and that have queued frames, add them to a a list of
2301 // released layers so we can properly set a fence.
2302 bool hasExistingOutputLayer =
2303 display->getOutputLayerForLayer(compositionLayer.get()) != nullptr;
2304 bool hasQueuedFrames = std::find(mLayersWithQueuedFrames.cbegin(),
2305 mLayersWithQueuedFrames.cend(),
2306 layer) != mLayersWithQueuedFrames.cend();
2307
2308 if (hasExistingOutputLayer && hasQueuedFrames) {
Chia-I Wu83806892017-11-16 10:50:20 -08002309 layersNeedingFences.add(layer);
2310 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002311 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002312 });
2313 }
Lloyd Piquecc01a452018-12-04 17:24:00 -08002314
2315 display->setOutputLayersOrderedByZ(std::move(layersSortedByZ));
2316
2317 displayDevice->setVisibleLayersSortedByZ(deprecated_layersSortedByZ);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002318 displayDevice->setLayersNeedingFences(layersNeedingFences);
2319
2320 Region undefinedRegion{bounds};
2321 undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2322
2323 display->editState().undefinedRegion = undefinedRegion;
2324 display->editState().dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002325 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002326 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002327}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002328
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002329// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002330// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002331// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002332// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002333// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002334// The returned HDR data space is one of
2335// - Dataspace::UNKNOWN
2336// - Dataspace::BT2020_HLG
2337// - Dataspace::BT2020_PQ
Peiyong Lin03912882019-04-16 15:34:46 -07002338Dataspace SurfaceFlinger::getBestDataspace(const sp<DisplayDevice>& display,
2339 Dataspace* outHdrDataSpace,
2340 bool* outIsHdrClientComposition) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002341 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002342 *outHdrDataSpace = Dataspace::UNKNOWN;
2343
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002344 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002345 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002346 case Dataspace::V0_SCRGB:
2347 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002348 case Dataspace::BT2020:
2349 case Dataspace::BT2020_ITU:
2350 case Dataspace::BT2020_LINEAR:
2351 case Dataspace::DISPLAY_BT2020:
2352 bestDataSpace = Dataspace::DISPLAY_BT2020;
2353 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002354 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002355 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002356 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002357 case Dataspace::BT2020_PQ:
2358 case Dataspace::BT2020_ITU_PQ:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002359 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002360 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lin03912882019-04-16 15:34:46 -07002361 *outIsHdrClientComposition = layer->getForceClientComposition(display);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002362 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002363 case Dataspace::BT2020_HLG:
2364 case Dataspace::BT2020_ITU_HLG:
Peiyong Linf6eb7662019-02-05 15:39:15 -08002365 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002366 // When there's mixed PQ content and HLG content, we set the HDR
2367 // data space to be BT2020_PQ and convert HLG to PQ.
2368 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2369 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002370 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002371 break;
2372 default:
2373 break;
2374 }
Romain Guy54f154a2017-10-24 21:40:32 +01002375 }
2376
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002377 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002378}
2379
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002380// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2382 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002383 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2384 *outMode = ColorMode::NATIVE;
2385 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002386 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002387 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002388 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002389
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002390 Dataspace hdrDataSpace;
Peiyong Lin03912882019-04-16 15:34:46 -07002391 bool isHdrClientComposition = false;
2392 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace, &isHdrClientComposition);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002393
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002394 auto* profile = display->getCompositionDisplay()->getDisplayColorProfile();
2395
Peiyong Lina3ea5592019-02-10 14:45:00 -08002396 switch (mForceColorMode) {
2397 case ColorMode::SRGB:
2398 bestDataSpace = Dataspace::V0_SRGB;
2399 break;
2400 case ColorMode::DISPLAY_P3:
2401 bestDataSpace = Dataspace::DISPLAY_P3;
2402 break;
2403 default:
2404 break;
2405 }
2406
Peiyong Lindfde5112018-06-05 10:58:41 -07002407 // respect hdrDataSpace only when there is no legacy HDR support
Peiyong Lin03912882019-04-16 15:34:46 -07002408 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
2409 !profile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002410 if (isHdr) {
2411 bestDataSpace = hdrDataSpace;
2412 }
2413
Chia-I Wu0d711262018-05-21 15:19:35 -07002414 RenderIntent intent;
2415 switch (mDisplayColorSetting) {
2416 case DisplayColorSetting::MANAGED:
2417 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002418 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002419 break;
2420 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002421 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002422 break;
2423 default: // vendor display color setting
2424 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2425 break;
2426 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002427
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07002428 profile->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002429}
2430
Lloyd Pique32cbe282018-10-19 13:09:22 -07002431void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& displayDevice) {
2432 auto display = displayDevice->getCompositionDisplay();
2433 const auto& displayState = display->getState();
2434
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002435 bool dirty = !display->getDirtyRegion(false).isEmpty();
Lloyd Pique32cbe282018-10-19 13:09:22 -07002436 bool empty = displayDevice->getVisibleLayersSortedByZ().size() == 0;
2437 bool wasEmpty = !displayState.lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002438
David Sodmanfa9b2af2017-12-24 13:28:59 -08002439 // If nothing has changed (!dirty), don't recompose.
2440 // If something changed, but we don't currently have any visible layers,
2441 // and didn't when we last did a composition, then skip it this time.
2442 // The second rule does two things:
2443 // - When all layers are removed from a display, we'll emit one black
2444 // frame, then nothing more until we get new layers.
2445 // - When a display is created with a private layer stack, we won't
2446 // emit any black frames until a layer is added to the layer stack.
2447 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002448
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 const char flagPrefix[] = {'-', '+'};
2450 static_cast<void>(flagPrefix);
Lloyd Pique32cbe282018-10-19 13:09:22 -07002451 ALOGV_IF(displayDevice->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2452 __FUNCTION__, mustRecompose ? "doing" : "skipping",
2453 displayDevice->getDebugName().c_str(), flagPrefix[dirty], flagPrefix[empty],
2454 flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002455
Lloyd Pique31cb2942018-10-19 17:23:03 -07002456 display->getRenderSurface()->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002457
David Sodmanfa9b2af2017-12-24 13:28:59 -08002458 if (mustRecompose) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002459 display->editState().lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002460 }
2461}
2462
Lloyd Pique32cbe282018-10-19 13:09:22 -07002463void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& displayDevice) {
2464 auto display = displayDevice->getCompositionDisplay();
2465 const auto& displayState = display->getState();
2466
2467 if (!displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002468 return;
David Sodman2b406362017-12-15 13:33:47 -08002469 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002470
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002471 status_t result = display->getRenderSurface()->prepareFrame();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002472 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
Lloyd Pique32cbe282018-10-19 13:09:22 -07002473 displayDevice->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002474}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002475
Lloyd Pique32cbe282018-10-19 13:09:22 -07002476void SurfaceFlinger::doComposition(const sp<DisplayDevice>& displayDevice, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002477 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002478 ALOGV("doComposition");
2479
Lloyd Pique32cbe282018-10-19 13:09:22 -07002480 auto display = displayDevice->getCompositionDisplay();
2481 const auto& displayState = display->getState();
2482
2483 if (displayState.isEnabled) {
David Sodmanfa9b2af2017-12-24 13:28:59 -08002484 // transform the dirty region into this screen's coordinate space
Alec Mourie7d1d4a2019-02-05 01:13:46 +00002485 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002486
David Sodmanfa9b2af2017-12-24 13:28:59 -08002487 // repaint the framebuffer (if needed)
Lloyd Pique32cbe282018-10-19 13:09:22 -07002488 doDisplayComposition(displayDevice, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002489
Lloyd Pique32cbe282018-10-19 13:09:22 -07002490 display->editState().dirtyRegion.clear();
Lloyd Pique31cb2942018-10-19 17:23:03 -07002491 display->getRenderSurface()->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002492 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002493 postFramebuffer(displayDevice);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002494}
2495
David Sodmanfa9b2af2017-12-24 13:28:59 -08002496void SurfaceFlinger::postFrame()
2497{
2498 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 const auto display = getDefaultDisplayDeviceLocked();
2500 if (display && getHwComposer().isConnected(*display->getId())) {
2501 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002502 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2503 logFrameStats();
2504 }
2505 }
2506}
2507
Lloyd Pique32cbe282018-10-19 13:09:22 -07002508void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& displayDevice) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002509 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002510 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002511
Lloyd Pique32cbe282018-10-19 13:09:22 -07002512 auto display = displayDevice->getCompositionDisplay();
2513 const auto& displayState = display->getState();
2514 const auto displayId = display->getId();
2515
Lloyd Pique32cbe282018-10-19 13:09:22 -07002516 if (displayState.isEnabled) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 if (displayId) {
2518 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002519 }
Lloyd Pique31cb2942018-10-19 17:23:03 -07002520 display->getRenderSurface()->onPresentDisplayCompleted();
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002521 for (auto& layer : display->getOutputLayersOrderedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002522 sp<Fence> releaseFence = Fence::NO_FENCE;
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002523 bool usedClientComposition = true;
David Sodman15094112018-10-11 09:39:37 -07002524
Chia-I Wu7b549592017-11-15 09:14:57 -08002525 // The layer buffer from the previous frame (if any) is released
2526 // by HWC only when the release fence from this frame (if any) is
2527 // signaled. Always get the release fence from HWC first.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002528 if (layer->getState().hwc) {
2529 const auto& hwcState = *layer->getState().hwc;
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08002530 releaseFence =
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002531 getHwComposer().getLayerReleaseFence(*displayId, hwcState.hwcLayer.get());
2532 usedClientComposition =
2533 hwcState.hwcCompositionType == Hwc2::IComposerClient::Composition::CLIENT;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002534 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002535
2536 // If the layer was client composited in the previous frame, we
2537 // need to merge with the previous client target acquire fence.
2538 // Since we do not track that, always merge with the current
2539 // client target acquire fence when it is available, even though
2540 // this is suboptimal.
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002541 if (usedClientComposition) {
Lloyd Pique31cb2942018-10-19 17:23:03 -07002542 releaseFence =
2543 Fence::merge("LayerRelease", releaseFence,
2544 display->getRenderSurface()->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002545 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002546
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002547 layer->getLayerFE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002548 }
Chia-I Wu83806892017-11-16 10:50:20 -08002549
2550 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002551 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002552 // supply them with the present fence.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002553 if (!displayDevice->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002554 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002555 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Lloyd Pique32cbe282018-10-19 13:09:22 -07002556 for (auto& layer : displayDevice->getLayersNeedingFences()) {
Lloyd Piquecb54b3b2019-01-29 18:42:54 -08002557 layer->getCompositionLayer()->getLayerFE()->onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002558 }
2559 }
2560
Dominik Laskowski075d3172018-05-24 15:50:06 -07002561 if (displayId) {
2562 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002563 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002564 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002565}
2566
Mathias Agopian87baae12012-07-31 12:38:26 -07002567void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568{
Mathias Agopian841cde52012-03-01 15:44:37 -08002569 ATRACE_CALL();
2570
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002571 // here we keep a copy of the drawing state (that is the state that's
2572 // going to be overwritten by handleTransactionLocked()) outside of
2573 // mStateLock so that the side-effects of the State assignment
2574 // don't happen with mStateLock held (which can cause deadlocks).
2575 State drawingState(mDrawingState);
2576
Mathias Agopianca4d3602011-05-19 15:38:14 -07002577 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002578 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579
Mathias Agopianca4d3602011-05-19 15:38:14 -07002580 // Here we're guaranteed that some transaction flags are set
2581 // so we can call handleTransactionLocked() unconditionally.
2582 // We call getTransactionFlags(), which will also clear the flags,
2583 // with mStateLock held to guarantee that mCurrentState won't change
2584 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002585
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002586 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002587 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002588 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002589
Mathias Agopianca4d3602011-05-19 15:38:14 -07002590 mDebugInTransaction = 0;
2591 invalidateHwcGeometry();
2592 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002593}
2594
Lloyd Piqueba04e622017-12-14 17:11:26 -08002595void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2596 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002597 const std::optional<DisplayIdentificationInfo> info =
2598 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002599
Dominik Laskowski075d3172018-05-24 15:50:06 -07002600 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002601 continue;
2602 }
2603
Lloyd Piqueba04e622017-12-14 17:11:26 -08002604 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002605 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002606 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 mPhysicalDisplayTokens[info->id] = new BBinder();
2608 DisplayDeviceState state;
2609 state.displayId = info->id;
2610 state.isSecure = true; // All physical displays are currently considered secure.
2611 state.displayName = info->name;
2612 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2613 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002614 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002615 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002616 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002617
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2619 if (index >= 0) {
2620 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2621 mInterceptor->saveDisplayDeletion(state.sequenceId);
2622 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002623 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002624 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002625 }
2626
2627 processDisplayChangesLocked();
2628 }
2629
2630 mPendingHotplugEvents.clear();
2631}
2632
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002633void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Ana Krulecc2870422019-01-29 19:00:58 -08002634 mScheduler->hotplugReceived(mAppConnectionHandle, displayId, connected);
2635 mScheduler->hotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002636}
2637
Lloyd Pique99d3da52018-01-22 17:48:03 -08002638sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002639 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002640 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002641 const sp<IGraphicBufferProducer>& producer) {
2642 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002643 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002644 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002645 creationArgs.isSecure = state.isSecure;
2646 creationArgs.displaySurface = dispSurface;
2647 creationArgs.hasWideColorGamut = false;
2648 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002649
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002650 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002651 creationArgs.isPrimary = isInternalDisplay;
2652
2653 if (useColorManagement && displayId) {
2654 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002655 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002656 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002657 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002658 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002659
Dominik Laskowski7e045462018-05-30 13:02:02 -07002660 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002661 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002662 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002663 }
tangrobin6753a022018-08-10 10:58:54 +08002664 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002665
Dominik Laskowski075d3172018-05-24 15:50:06 -07002666 if (displayId) {
2667 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002668 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002669 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002670 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002671
Lloyd Pique90c115d2018-09-18 21:39:42 -07002672 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002673 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002674 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002675
Lloyd Pique99d3da52018-01-22 17:48:03 -08002676 // Make sure that composition can never be stalled by a virtual display
2677 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002678 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002679 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002680 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2681 }
2682
Dominik Laskowski075d3172018-05-24 15:50:06 -07002683 creationArgs.displayInstallOrientation =
2684 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002685
Lloyd Pique99d3da52018-01-22 17:48:03 -08002686 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002687 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002688
Lloyd Pique90c115d2018-09-18 21:39:42 -07002689 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002690
2691 if (maxFrameBufferAcquiredBuffers >= 3) {
2692 nativeWindowSurface->preallocateBuffers();
2693 }
2694
2695 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002696 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002697 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002698 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002699 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002700 }
Lloyd Pique32cbe282018-10-19 13:09:22 -07002701 display->getCompositionDisplay()->setColorMode(defaultColorMode, defaultDataSpace,
2702 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002703 if (!state.isVirtual()) {
2704 LOG_ALWAYS_FATAL_IF(!displayId);
2705 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002706 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002707
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002708 display->setLayerStack(state.layerStack);
2709 display->setProjection(state.orientation, state.viewport, state.frame);
2710 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002711
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002712 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002713}
2714
Lloyd Pique347200f2017-12-14 17:00:15 -08002715void SurfaceFlinger::processDisplayChangesLocked() {
2716 // here we take advantage of Vector's copy-on-write semantics to
2717 // improve performance by skipping the transaction entirely when
2718 // know that the lists are identical
2719 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2720 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2721 if (!curr.isIdenticalTo(draw)) {
2722 mVisibleRegionsDirty = true;
2723 const size_t cc = curr.size();
2724 size_t dc = draw.size();
2725
2726 // find the displays that were removed
2727 // (ie: in drawing state but not in current state)
2728 // also handle displays that changed
2729 // (ie: displays that are in both lists)
2730 for (size_t i = 0; i < dc;) {
2731 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2732 if (j < 0) {
2733 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002734 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002735 // Save display ID before disconnecting.
2736 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002737 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002738
2739 if (!display->isVirtual()) {
2740 LOG_ALWAYS_FATAL_IF(!displayId);
2741 dispatchDisplayHotplugEvent(displayId->value, false);
2742 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002743 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002744
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002745 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002746 } else {
2747 // this display is in both lists. see if something changed.
2748 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002750 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2751 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2752 if (state_binder != draw_binder) {
2753 // changing the surface is like destroying and
2754 // recreating the DisplayDevice, so we just remove it
2755 // from the drawing state, so that it get re-added
2756 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002757 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002758 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002759 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002760 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002761 mDrawingState.displays.removeItemsAt(i);
2762 dc--;
2763 // at this point we must loop to the next item
2764 continue;
2765 }
2766
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002767 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002768 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002769 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002770 }
2771 if ((state.orientation != draw[i].orientation) ||
2772 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002773 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002774 }
2775 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002776 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002777 }
2778 }
2779 }
2780 ++i;
2781 }
2782
2783 // find displays that were added
2784 // (ie: in current state but not in drawing state)
2785 for (size_t i = 0; i < cc; i++) {
2786 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2787 const DisplayDeviceState& state(curr[i]);
2788
Lloyd Pique542307f2018-10-19 13:24:08 -07002789 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002790 sp<IGraphicBufferProducer> producer;
2791 sp<IGraphicBufferProducer> bqProducer;
2792 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002793 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002794
Dominik Laskowski075d3172018-05-24 15:50:06 -07002795 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002796 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002797 // Virtual displays without a surface are dormant:
2798 // they have external state (layer stack, projection,
2799 // etc.) but no internal state (i.e. a DisplayDevice).
2800 if (state.surface != nullptr) {
2801 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002802 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002803 int width = 0;
2804 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2805 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2806 int height = 0;
2807 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2808 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2809 int intFormat = 0;
2810 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2811 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002812 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002813
Dominik Laskowski075d3172018-05-24 15:50:06 -07002814 displayId =
2815 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002816 }
2817
2818 // TODO: Plumb requested format back up to consumer
2819
2820 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002821 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002822 bqProducer, bqConsumer,
2823 state.displayName);
2824
2825 dispSurface = vds;
2826 producer = vds;
2827 }
2828 } else {
2829 ALOGE_IF(state.surface != nullptr,
2830 "adding a supported display, but rendering "
2831 "surface is provided (%p), ignoring it",
2832 state.surface.get());
2833
Dominik Laskowski075d3172018-05-24 15:50:06 -07002834 displayId = state.displayId;
2835 LOG_ALWAYS_FATAL_IF(!displayId);
2836 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002837 producer = bqProducer;
2838 }
2839
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002840 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002841 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002842 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002843 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002844 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002845 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002846 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002847 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002848 }
2849 }
2850 }
2851 }
2852 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002853
2854 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002855}
2856
Mathias Agopian87baae12012-07-31 12:38:26 -07002857void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002858{
Dan Stoza7dde5992015-05-22 09:51:44 -07002859 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002860 mCurrentState.traverseInZOrder([](Layer* layer) {
2861 layer->notifyAvailableFrames();
2862 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002863
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 /*
2865 * Traversal of the children
2866 * (perform the transaction for each of them if needed)
2867 */
2868
Marissa Wall06255332019-03-27 13:48:27 -07002869 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002870 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002871 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002872 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002873
2874 const uint32_t flags = layer->doTransaction(0);
2875 if (flags & Layer::eVisibleRegion)
2876 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002877
2878 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002879 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002880 }
Robert Carr2047fae2016-11-28 14:09:09 -08002881 });
Marissa Wall06255332019-03-27 13:48:27 -07002882 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002883 }
2884
2885 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002886 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002887 */
2888
Mathias Agopiane57f2922012-08-09 16:29:12 -07002889 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002890 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002891 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002892 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002893
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002894 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002895 // The transform hint might have changed for some layers
2896 // (either because a display has changed, or because a layer
2897 // as changed).
2898 //
2899 // Walk through all the layers in currentLayers,
2900 // and update their transform hint.
2901 //
2902 // If a layer is visible only on a single display, then that
2903 // display is used to calculate the hint, otherwise we use the
2904 // default display.
2905 //
2906 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2907 // the hint is set before we acquire a buffer from the surface texture.
2908 //
2909 // NOTE: layer transactions have taken place already, so we use their
2910 // drawing state. However, SurfaceFlinger's own transaction has not
2911 // happened yet, so we must use the current state layer list
2912 // (soon to become the drawing state list).
2913 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002914 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002915 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002916 bool first = true;
2917 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002918 // NOTE: we rely on the fact that layers are sorted by
2919 // layerStack first (so we don't have to traverse the list
2920 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002922 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002923 currentlayerStack = layerStack;
2924 // figure out if this layerstack is mirrored
2925 // (more than one display) if so, pick the default display,
2926 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002927 hintDisplay = nullptr;
2928 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002929 if (display->getCompositionDisplay()
2930 ->belongsInOutput(layer->getLayerStack(),
2931 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002932 if (hintDisplay) {
2933 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002934 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002935 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002936 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002937 }
2938 }
2939 }
2940 }
Chet Haase91d25932013-04-11 15:24:55 -07002941
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002942 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002943 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2944 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002945
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002946 // could be null when this layer is using a layerStack
2947 // that is not visible on any display. Also can occur at
2948 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002949 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002950 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002951
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002952 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002953 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002954 if (hintDisplay) {
2955 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002956 }
Robert Carr2047fae2016-11-28 14:09:09 -08002957
2958 first = false;
2959 });
Mathias Agopian84300952012-11-21 16:02:13 -08002960 }
2961
2962
Mathias Agopian3559b072012-08-15 13:46:03 -07002963 /*
2964 * Perform our own transaction if needed
2965 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002966
2967 if (mLayersAdded) {
2968 mLayersAdded = false;
2969 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002970 mVisibleRegionsDirty = true;
2971 }
2972
2973 // some layers might have been removed, so
2974 // we need to update the regions they're exposing.
2975 if (mLayersRemoved) {
2976 mLayersRemoved = false;
2977 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002978 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002979 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002980 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002981 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002982 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002983 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002984 }
Robert Carr2047fae2016-11-28 14:09:09 -08002985 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986 }
2987
Vishnu Nairec0ab382019-02-13 15:32:56 -08002988 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002990}
2991
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002992void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002993 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002994 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002995 return;
2996 }
2997
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002998 if (mVisibleRegionsDirty || mInputInfoChanged) {
2999 mInputInfoChanged = false;
3000 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08003001 } else if (mInputWindowCommands.syncInputWindows) {
3002 // If the caller requested to sync input windows, but there are no
3003 // changes to input windows, notify immediately.
3004 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003005 }
3006
3007 executeInputWindowCommands();
3008}
3009
3010void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003011 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07003012
3013 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
3014 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08003015 // When calculating the screen bounds we ignore the transparent region since it may
3016 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003017 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07003018 }
3019 });
chaviw291d88a2019-02-14 10:33:58 -08003020
3021 mInputFlinger->setInputWindows(inputHandles,
3022 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
3023 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07003024}
3025
Vishnu Nairec0ab382019-02-13 15:32:56 -08003026void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07003027 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08003028 mPendingInputWindowCommands.clear();
3029}
3030
chaviwfbe5d9c2018-12-26 12:23:37 -08003031void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08003032 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
3033 if (transferTouchFocusCommand.fromToken != nullptr &&
3034 transferTouchFocusCommand.toToken != nullptr &&
3035 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
3036 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
3037 transferTouchFocusCommand.toToken);
3038 }
3039 }
3040
3041 mInputWindowCommands.clear();
3042}
3043
Riley Andrews03414a12014-07-01 14:22:59 -07003044void SurfaceFlinger::updateCursorAsync()
3045{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003046 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003047 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07003048 continue;
3049 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003051 for (auto& layer : display->getVisibleLayersSortedByZ()) {
3052 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07003053 }
3054 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003055}
3056
chaviw61626f22018-11-15 16:26:27 -08003057void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
3058 if (layer->hasReadyFrame()) {
Robert Carra0629232019-02-07 15:28:54 -08003059 bool ignored = false;
Alec Mouri56e538f2019-01-14 15:22:01 -08003060 layer->latchBuffer(ignored, systemTime());
chaviw61626f22018-11-15 16:26:27 -08003061 }
3062 layer->releasePendingBuffer(systemTime());
3063}
3064
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065void SurfaceFlinger::commitTransaction()
3066{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003067 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07003068 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07003069 for (const auto& l : mLayersPendingRemoval) {
3070 recordBufferingStats(l->getName().string(),
3071 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07003072
Lloyd Pique07e33212018-12-18 16:33:37 -08003073 // Ensure any buffers set to display on any children are released.
Robert Carr2e102c92018-10-23 12:11:15 -07003074 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003075 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07003076 }
chaviw74d90ad2019-04-26 14:45:26 -07003077
3078 // If the layer has been removed and has no parent, then it will not be reachable
3079 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3080 // ensure we can copy its current to drawing state.
3081 if (!l->getParent()) {
3082 mOffscreenLayers.emplace(l.get());
3083 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003084 }
3085 mLayersPendingRemoval.clear();
3086 }
3087
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003088 // If this transaction is part of a window animation then the next frame
3089 // we composite should be considered an animation as well.
3090 mAnimCompositionPending = mAnimTransactionPending;
3091
Nataniel Borges2b796da2019-02-15 13:32:18 -08003092 withTracingLock([&]() {
3093 mDrawingState = mCurrentState;
3094 // clear the "changed" flags in current state
3095 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07003096
chaviw74d90ad2019-04-26 14:45:26 -07003097 mDrawingState.traverseInZOrder([&](Layer* layer) {
3098 layer->commitChildList();
3099
3100 // If the layer can be reached when traversing mDrawingState, then the layer is no
3101 // longer offscreen. Remove the layer from the offscreenLayer set.
3102 if (mOffscreenLayers.count(layer)) {
3103 mOffscreenLayers.erase(layer);
3104 }
3105 });
3106
3107 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003108 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08003109
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003110 mTransactionPending = false;
3111 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003112 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003113}
3114
Nataniel Borges2b796da2019-02-15 13:32:18 -08003115void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3116 if (mTracingEnabledChanged) {
3117 mTracingEnabled = mTracing.isEnabled();
3118 mTracingEnabledChanged = false;
3119 }
3120
3121 // Synchronize with Tracing thread
3122 std::unique_lock<std::mutex> lock;
3123 if (mTracingEnabled) {
3124 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3125 }
3126
3127 lockedOperation();
3128
3129 // Synchronize with Tracing thread
3130 if (mTracingEnabled) {
3131 lock.unlock();
3132 }
3133}
3134
chaviw74d90ad2019-04-26 14:45:26 -07003135void SurfaceFlinger::commitOffscreenLayers() {
3136 for (Layer* offscreenLayer : mOffscreenLayers) {
3137 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
3138 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3139 if (!trFlags) return;
3140
3141 layer->doTransaction(0);
3142 layer->commitChildList();
3143 });
3144 }
3145}
3146
Lloyd Pique32cbe282018-10-19 13:09:22 -07003147void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003148 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08003149 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003150 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08003151
Lloyd Pique32cbe282018-10-19 13:09:22 -07003152 auto display = displayDevice->getCompositionDisplay();
3153
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003154 Region aboveOpaqueLayers;
3155 Region aboveCoveredLayers;
3156 Region dirty;
3157
Mathias Agopian87baae12012-07-31 12:38:26 -07003158 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003159
Robert Carr2047fae2016-11-28 14:09:09 -08003160 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003161 // start with the whole surface at its current location
3162 const Layer::State& s(layer->getDrawingState());
3163
Jesse Hall01e29052013-02-19 16:13:35 -08003164 // only consider the layers on the given layer stack
Lloyd Piqueef36b002019-01-23 17:52:04 -08003165 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Robert Carr2047fae2016-11-28 14:09:09 -08003166 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003167 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003168
Mathias Agopianab028732010-03-16 16:41:46 -07003169 /*
3170 * opaqueRegion: area of a surface that is fully opaque.
3171 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003172 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003173
3174 /*
3175 * visibleRegion: area of a surface that is visible on screen
3176 * and not fully transparent. This is essentially the layer's
3177 * footprint minus the opaque regions above it.
3178 * Areas covered by a translucent surface are considered visible.
3179 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003181
3182 /*
3183 * coveredRegion: area of a surface that is covered by all
3184 * visible regions above it (which includes the translucent areas).
3185 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003187
Jesse Halla8026d22012-09-25 13:25:04 -07003188 /*
3189 * transparentRegion: area of a surface that is hinted to be completely
3190 * transparent. This is only used to tell when the layer has no visible
3191 * non-transparent regions and can be removed from the layer list. It
3192 * does not affect the visibleRegion of this layer or any layers
3193 * beneath it. The hint may not be correct if apps don't respect the
3194 * SurfaceView restrictions (which, sadly, some don't).
3195 */
3196 Region transparentRegion;
3197
Mathias Agopianab028732010-03-16 16:41:46 -07003198
3199 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07003200 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003201 const bool translucent = !layer->isOpaque(s);
Vishnu Nair4351ad52019-02-11 14:13:02 -08003202 Rect bounds(layer->getScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07003203
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07003205 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07003206 if (!visibleRegion.isEmpty()) {
3207 // Remove the transparent area from the visible region
3208 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003209 if (tr.preserveRects()) {
3210 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003211 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07003212 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07003213 // transformation too complex, can't do the
3214 // transparent region optimization.
3215 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07003216 }
Mathias Agopianab028732010-03-16 16:41:46 -07003217 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003218
Mathias Agopianab028732010-03-16 16:41:46 -07003219 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07003220 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02003221 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003222 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07003223 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07003224 // the opaque region is the layer's footprint
3225 opaqueRegion = visibleRegion;
3226 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003227 }
3228 }
3229
Robert Carre5f4f692018-01-12 13:12:28 -08003230 if (visibleRegion.isEmpty()) {
3231 layer->clearVisibilityRegions();
3232 return;
3233 }
3234
Mathias Agopianab028732010-03-16 16:41:46 -07003235 // Clip the covered region to the visible region
3236 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3237
3238 // Update aboveCoveredLayers for next (lower) layer
3239 aboveCoveredLayers.orSelf(visibleRegion);
3240
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003241 // subtract the opaque region covered by the layers above us
3242 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003243
3244 // compute this layer's dirty region
3245 if (layer->contentDirty) {
3246 // we need to invalidate the whole region
3247 dirty = visibleRegion;
3248 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003249 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003250 layer->contentDirty = false;
3251 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003252 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003253 * the exposed region consists of two components:
3254 * 1) what's VISIBLE now and was COVERED before
3255 * 2) what's EXPOSED now less what was EXPOSED before
3256 *
3257 * note that (1) is conservative, we start with the whole
3258 * visible region but only keep what used to be covered by
3259 * something -- which mean it may have been exposed.
3260 *
3261 * (2) handles areas that were not covered by anything but got
3262 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003263 */
Mathias Agopianab028732010-03-16 16:41:46 -07003264 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003265 const Region oldVisibleRegion = layer->visibleRegion;
3266 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003267 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3268 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 }
3270 dirty.subtractSelf(aboveOpaqueLayers);
3271
3272 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003273 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274
Mathias Agopianab028732010-03-16 16:41:46 -07003275 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003277
Jesse Halla8026d22012-09-25 13:25:04 -07003278 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003279 layer->setVisibleRegion(visibleRegion);
3280 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003281 layer->setVisibleNonTransparentRegion(
3282 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003283 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003284
Mathias Agopian87baae12012-07-31 12:38:26 -07003285 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286}
3287
Chia-I Wuab0c3192017-08-01 11:29:00 -07003288void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003289 for (const auto& [token, displayDevice] : mDisplays) {
3290 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003291 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003292 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003293 }
3294 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003295}
3296
Dan Stoza6b9454d2014-11-07 16:00:59 -08003297bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003298{
Ady Abraham09bd3922019-04-08 10:44:56 -07003299 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003300 ALOGV("handlePageFlip");
3301
Brian Andersond6927fb2016-07-23 23:37:30 -07003302 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303
Mathias Agopian4fec8732012-06-29 14:12:52 -07003304 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003305 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003306 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003307
3308 // Store the set of layers that need updates. This set must not change as
3309 // buffers are being latched, as this could result in a deadlock.
3310 // Example: Two producers share the same command stream and:
3311 // 1.) Layer 0 is latched
3312 // 2.) Layer 0 gets a new frame
3313 // 2.) Layer 1 gets a new frame
3314 // 3.) Layer 1 is latched.
3315 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3316 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003317 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003318 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003319 frameQueued = true;
Alec Mouriaa614192019-06-06 13:28:34 -07003320 const nsecs_t expectedPresentTime = getExpectedPresentTime();
Ana Krulec010d2192018-10-08 06:29:54 -07003321 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003322 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003323 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003324 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003325 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003326 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003327 } else {
3328 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003329 }
Robert Carr2047fae2016-11-28 14:09:09 -08003330 });
3331
Lloyd Piquef2c79392018-12-20 16:23:33 -08003332 if (!mLayersWithQueuedFrames.empty()) {
3333 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3334 // writes to Layer current state. See also b/119481871
3335 Mutex::Autolock lock(mStateLock);
3336
3337 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri56e538f2019-01-14 15:22:01 -08003338 if (layer->latchBuffer(visibleRegions, latchTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003339 mLayersPendingRefresh.push_back(layer);
3340 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003341 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003342 if (layer->isBufferLatched()) {
3343 newDataLatched = true;
3344 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003345 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003346 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003347
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003348 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003349
3350 // If we will need to wake up at some time in the future to deal with a
3351 // queued frame that shouldn't be displayed during this vsync period, wake
3352 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003353 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003354 signalLayerUpdate();
3355 }
3356
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003357 // enter boot animation on first buffer latch
3358 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3359 ALOGI("Enter boot animation");
3360 mBootStage = BootStage::BOOTANIMATION;
3361 }
3362
Dan Stoza6b9454d2014-11-07 16:00:59 -08003363 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003364 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003365}
3366
Mathias Agopianad456f92011-01-13 17:53:01 -08003367void SurfaceFlinger::invalidateHwcGeometry()
3368{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003369 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003370}
3371
Lloyd Pique32cbe282018-10-19 13:09:22 -07003372void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& displayDevice,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003373 const Region& inDirtyRegion) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003374 auto display = displayDevice->getCompositionDisplay();
Dan Stoza71433162014-02-04 16:22:36 -08003375 // We only need to actually compose the display if:
3376 // 1) It is being handled by hardware composer, which may need this to
3377 // keep its virtual display state machine in sync, or
3378 // 2) There is work to be done (the dirty region isn't empty)
Lloyd Pique32cbe282018-10-19 13:09:22 -07003379 if (!displayDevice->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003380 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003381 return;
3382 }
3383
Dan Stoza9e56aa02015-11-02 13:00:03 -08003384 ALOGV("doDisplayComposition");
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003385 base::unique_fd readyFence;
3386 if (!doComposeSurfaces(displayDevice, Region::INVALID_REGION, &readyFence)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003387
3388 // swap buffers (presentation)
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003389 display->getRenderSurface()->queueBuffer(std::move(readyFence));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003390}
3391
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003392bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& displayDevice,
3393 const Region& debugRegion, base::unique_fd* readyFence) {
Alec Mouri820c7402019-01-23 13:02:39 -08003394 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003395 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003396
Lloyd Pique32cbe282018-10-19 13:09:22 -07003397 auto display = displayDevice->getCompositionDisplay();
3398 const auto& displayState = display->getState();
Dominik Laskowski7e045462018-05-30 13:02:02 -07003399 const auto displayId = display->getId();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003400 auto& renderEngine = getRenderEngine();
Peiyong Lin548d4fa2019-04-02 18:14:44 -07003401 const bool supportProtectedContent = renderEngine.supportsProtectedContent();
Lloyd Pique32cbe282018-10-19 13:09:22 -07003402
3403 const Region bounds(displayState.bounds);
3404 const DisplayRenderArea renderArea(displayDevice);
Lloyd Pique441d5042018-10-18 16:49:51 -07003405 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003406 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003407
Chia-I Wu8e50e692018-05-04 10:12:37 -07003408 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003409
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003410 renderengine::DisplaySettings clientCompositionDisplay;
3411 std::vector<renderengine::LayerSettings> clientCompositionLayers;
3412 sp<GraphicBuffer> buf;
Alec Mouri6338c9d2019-02-07 16:57:51 -08003413 base::unique_fd fd;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003414
Dan Stoza9e56aa02015-11-02 13:00:03 -08003415 if (hasClientComposition) {
3416 ALOGV("hasClientComposition");
3417
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003418 if (displayDevice->isPrimary() && supportProtectedContent) {
3419 bool needsProtected = false;
3420 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
3421 // If the layer is a protected layer, mark protected context is needed.
3422 if (layer->isProtected()) {
3423 needsProtected = true;
3424 break;
3425 }
3426 }
Peiyong Lin52010312019-05-02 14:22:16 -07003427 if (needsProtected != renderEngine.isProtected()) {
3428 renderEngine.useProtectedContext(needsProtected);
3429 }
3430 if (needsProtected != display->getRenderSurface()->isProtected() &&
3431 needsProtected == renderEngine.isProtected()) {
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003432 display->getRenderSurface()->setProtected(needsProtected);
3433 }
3434 }
3435
Alec Mouri6338c9d2019-02-07 16:57:51 -08003436 buf = display->getRenderSurface()->dequeueBuffer(&fd);
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003437
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003438 if (buf == nullptr) {
3439 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3440 "client composition for this frame",
Lloyd Pique32cbe282018-10-19 13:09:22 -07003441 displayDevice->getDisplayName().c_str());
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003442 return false;
3443 }
3444
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003445 clientCompositionDisplay.physicalDisplay = displayState.scissor;
3446 clientCompositionDisplay.clip = displayState.scissor;
3447 const ui::Transform& displayTransform = displayState.transform;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07003448 clientCompositionDisplay.globalTransform = displayTransform.asMatrix4();
Peiyong Linb1925962019-04-01 16:37:10 -07003449 clientCompositionDisplay.orientation = displayState.orientation;
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003450
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003451 const auto* profile = display->getDisplayColorProfile();
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003452 Dataspace outputDataspace = Dataspace::UNKNOWN;
Lloyd Pique3d0c02e2018-10-19 18:38:12 -07003453 if (profile->hasWideColorGamut()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003454 outputDataspace = displayState.dataspace;
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003455 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003456 clientCompositionDisplay.outputDataspace = outputDataspace;
3457 clientCompositionDisplay.maxLuminance =
3458 profile->getHdrCapabilities().getDesiredMaxLuminance();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003459
Lloyd Pique441d5042018-10-18 16:49:51 -07003460 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003461 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003462 getHwComposer()
3463 .hasDisplayCapability(displayId,
3464 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003465
Peiyong Lind3788632018-09-18 16:01:31 -07003466 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003467 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3468 if (applyColorMatrix) {
Alec Mouric7e8ce82019-04-02 12:28:05 -07003469 clientCompositionDisplay.colorTransform = displayState.colorTransformMat;
Mathias Agopianf45c5102012-10-24 16:29:17 -07003470 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003471 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003472
Mathias Agopian85d751c2012-08-29 16:59:24 -07003473 /*
3474 * and then, render the layers targeted at the framebuffer
3475 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003476
Dan Stoza9e56aa02015-11-02 13:00:03 -08003477 ALOGV("Rendering client layers");
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003478 bool firstLayer = true;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003479 Region clearRegion = Region::INVALID_REGION;
Lloyd Pique32cbe282018-10-19 13:09:22 -07003480 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003481 const Region viewportRegion(displayState.viewport);
3482 const Region clip(viewportRegion.intersect(layer->visibleRegion));
David Sodmanc1498e62018-09-12 14:36:26 -07003483 ALOGV("Layer: %s", layer->getName().string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003484 ALOGV(" Composition type: %s", toString(layer->getCompositionType(displayDevice)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003485 if (!clip.isEmpty()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003486 switch (layer->getCompositionType(displayDevice)) {
3487 case Hwc2::IComposerClient::Composition::CURSOR:
3488 case Hwc2::IComposerClient::Composition::DEVICE:
3489 case Hwc2::IComposerClient::Composition::SIDEBAND:
3490 case Hwc2::IComposerClient::Composition::SOLID_COLOR: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003491 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003492 const Layer::State& state(layer->getDrawingState());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003493 if (layer->getClearClientTarget(displayDevice) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003494 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003495 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003496 // never clear the very first layer since we're
3497 // guaranteed the FB is already cleared
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003498 renderengine::LayerSettings layerSettings;
3499 Region dummyRegion;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003500 bool prepared =
3501 layer->prepareClientLayer(renderArea, clip, dummyRegion,
3502 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003503
3504 if (prepared) {
3505 layerSettings.source.buffer.buffer = nullptr;
3506 layerSettings.source.solidColor = half3(0.0, 0.0, 0.0);
3507 layerSettings.alpha = half(0.0);
3508 layerSettings.disableBlending = true;
3509 clientCompositionLayers.push_back(layerSettings);
3510 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07003511 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003512 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003513 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08003514 case Hwc2::IComposerClient::Composition::CLIENT: {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003515 renderengine::LayerSettings layerSettings;
3516 bool prepared =
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003517 layer->prepareClientLayer(renderArea, clip, clearRegion,
3518 supportProtectedContent, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003519 if (prepared) {
3520 clientCompositionLayers.push_back(layerSettings);
Peiyong Lind3788632018-09-18 16:01:31 -07003521 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003522 break;
3523 }
3524 default:
3525 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003526 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003527 } else {
3528 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003529 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003530 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003531 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003532
Alec Mouri820c7402019-01-23 13:02:39 -08003533 // Perform some cleanup steps if we used client composition.
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003534 if (hasClientComposition) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003535 clientCompositionDisplay.clearRegion = clearRegion;
Peiyong Lin74ca2f42019-01-14 19:36:57 -08003536
3537 // We boost GPU frequency here because there will be color spaces conversion
3538 // and it's expensive. We boost the GPU frequency so that GPU composition can
3539 // finish in time. We must reset GPU frequency afterwards, because high frequency
3540 // consumes extra battery.
3541 const bool expensiveRenderingExpected =
3542 clientCompositionDisplay.outputDataspace == Dataspace::DISPLAY_P3;
3543 if (expensiveRenderingExpected && displayId) {
3544 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, true);
3545 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00003546 if (!debugRegion.isEmpty()) {
3547 Region::const_iterator it = debugRegion.begin();
3548 Region::const_iterator end = debugRegion.end();
3549 while (it != end) {
3550 const Rect& rect = *it++;
3551 renderengine::LayerSettings layerSettings;
3552 layerSettings.source.buffer.buffer = nullptr;
3553 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
3554 layerSettings.geometry.boundaries = rect.toFloatRect();
3555 layerSettings.alpha = half(1.0);
3556 clientCompositionLayers.push_back(layerSettings);
3557 }
3558 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08003559 renderEngine.drawLayers(clientCompositionDisplay, clientCompositionLayers,
Alec Mourife0d72b2019-03-21 14:05:56 -07003560 buf->getNativeBuffer(), /*useFramebufferCache=*/true, std::move(fd),
3561 readyFence);
Peiyong Lin8ec87f82019-04-05 11:30:51 -07003562 } else if (displayId) {
3563 mPowerAdvisor.setExpensiveRenderingExpected(*displayId, false);
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003564 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003565 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003566}
3567
Chia-I Wu28e3a252018-09-07 12:05:02 -07003568void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003569 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003570 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571}
3572
Robert Carrc0df3122019-04-11 13:18:21 -07003573status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3574 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3575 const sp<IBinder>& parentHandle,
3576 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003577 // add this layer to the current state list
3578 {
3579 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003580 sp<Layer> parent;
3581 if (parentHandle != nullptr) {
3582 parent = fromHandle(parentHandle);
3583 if (parent == nullptr) {
3584 return NAME_NOT_FOUND;
3585 }
3586 } else {
3587 parent = parentLayer;
3588 }
3589
Robert Carr1f0a16a2016-10-24 16:27:39 -07003590 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003591 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3592 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003593 return NO_MEMORY;
3594 }
Robert Carrc0df3122019-04-11 13:18:21 -07003595
3596 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3597
Robert Carrb89ea9d2018-12-10 13:01:14 -08003598 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003599 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003600 } else if (parent == nullptr) {
3601 lbc->onRemovedFromCurrentState();
3602 } else if (parent->isRemovedFromCurrentState()) {
3603 parent->addChild(lbc);
3604 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003605 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003606 parent->addChild(lbc);
3607 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003608
Yiwei Zhang243b3782018-05-15 17:40:04 -07003609 if (gbc != nullptr) {
3610 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3611 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3612 mMaxGraphicBufferProducerListSize,
3613 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3614 mGraphicBufferProducerList.size(),
3615 mMaxGraphicBufferProducerListSize, mNumLayers);
3616 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003617 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003618 }
3619
Mathias Agopian96f08192010-06-02 23:28:45 -07003620 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003621 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003622
Dan Stoza7d89d062015-04-30 13:29:25 -07003623 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003624}
3625
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003626uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003627 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003628}
3629
Mathias Agopian3f844832013-08-07 21:24:32 -07003630uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003631 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003632}
3633
Mathias Agopian3f844832013-08-07 21:24:32 -07003634uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003635 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003636}
3637
3638uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003639 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003640 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003641 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003642 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003643 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003644 }
3645 return old;
3646}
3647
Marissa Wall713b63f2018-10-17 15:42:43 -07003648bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003649 // to prevent onHandleDestroyed from being called while the lock is held,
3650 // we must keep a copy of the transactions (specifically the composer
3651 // states) around outside the scope of the lock
3652 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003653 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003654 {
3655 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003656
Valerie Haufce31b82019-04-30 16:41:14 -07003657 auto it = mTransactionQueues.begin();
3658 while (it != mTransactionQueues.end()) {
3659 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003660
Valerie Haufce31b82019-04-30 16:41:14 -07003661 while (!transactionQueue.empty()) {
3662 const auto& transaction = transactionQueue.front();
3663 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
3664 transaction.states)) {
3665 setTransactionFlags(eTransactionFlushNeeded);
3666 break;
3667 }
3668 transactions.push_back(transaction);
3669 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3670 mPendingInputWindowCommands, transaction.desiredPresentTime,
3671 transaction.buffer, transaction.callback,
3672 transaction.postTime, transaction.privileged,
3673 /*isMainThread*/ true);
3674 transactionQueue.pop();
3675 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003676 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003677
Valerie Haufce31b82019-04-30 16:41:14 -07003678 if (transactionQueue.empty()) {
3679 it = mTransactionQueues.erase(it);
3680 mTransactionCV.broadcast();
3681 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003682 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003683 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003684 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003685 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003686 return flushedATransaction;
3687}
3688
3689bool SurfaceFlinger::transactionFlushNeeded() {
3690 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003691}
3692
chaviwca27f252018-02-06 16:46:39 -08003693bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3694 for (const ComposerState& state : states) {
3695 // Here we need to check that the interface we're given is indeed
3696 // one of our own. A malicious client could give us a nullptr
3697 // IInterface, or one of its own or even one of our own but a
3698 // different type. All these situations would cause us to crash.
3699 if (state.client == nullptr) {
3700 return true;
3701 }
3702
3703 sp<IBinder> binder = IInterface::asBinder(state.client);
3704 if (binder == nullptr) {
3705 return true;
3706 }
3707
3708 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3709 return true;
3710 }
3711 }
3712 return false;
3713}
3714
Marissa Wall17b4e452018-12-26 16:32:34 -08003715bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
3716 const Vector<ComposerState>& states) {
Ady Abraham8fe11022019-06-12 17:11:12 -07003717 nsecs_t expectedPresentTime = getExpectedPresentTime();
Marissa Wall17b4e452018-12-26 16:32:34 -08003718 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3719 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3720 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3721 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3722 return false;
3723 }
3724
Marissa Wall713b63f2018-10-17 15:42:43 -07003725 for (const ComposerState& state : states) {
3726 const layer_state_t& s = state.state;
3727 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3728 continue;
3729 }
3730 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003731 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003732 }
3733 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003734 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003735}
3736
3737void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3738 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003739 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08003740 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003741 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003742 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003743 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003744 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003745
Valerie Haubc6ddb12019-03-08 11:10:15 -08003746 const int64_t postTime = systemTime();
3747
Robert Carr14167e02019-02-13 13:50:55 -08003748 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3749
Mathias Agopian698c0872011-06-28 19:09:31 -07003750 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003751
chaviwca27f252018-02-06 16:46:39 -08003752 if (containsAnyInvalidClientState(states)) {
3753 return;
3754 }
3755
Marissa Wall713b63f2018-10-17 15:42:43 -07003756 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003757 auto itr = mTransactionQueues.find(applyToken);
3758 // if this is an animation frame, wait until prior animation frame has
3759 // been applied by SF
3760 if (flags & eAnimation) {
3761 while (itr != mTransactionQueues.end()) {
3762 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3763 if (CC_UNLIKELY(err != NO_ERROR)) {
3764 ALOGW_IF(err == TIMED_OUT,
3765 "setTransactionState timed out "
3766 "waiting for animation frame to apply");
3767 break;
3768 }
3769 itr = mTransactionQueues.find(applyToken);
3770 }
3771 }
3772 if (itr != mTransactionQueues.end() ||
Marissa Wall17b4e452018-12-26 16:32:34 -08003773 !transactionIsReadyToBeApplied(desiredPresentTime, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003774 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003775 uncacheBuffer, listenerCallbacks, postTime,
3776 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003777 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003778 return;
3779 }
3780
Valerie Haubc6ddb12019-03-08 11:10:15 -08003781 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003782 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07003783}
3784
3785void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003786 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08003787 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07003788 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07003789 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07003790 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07003791 const int64_t postTime, bool privileged,
3792 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003793 uint32_t transactionFlags = 0;
3794
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003795 if (flags & eAnimation) {
3796 // For window updates that are part of an animation we must wait for
3797 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003798 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003799 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003800 if (CC_UNLIKELY(err != NO_ERROR)) {
3801 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003802 // caller after a few seconds.
3803 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3804 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003805 mAnimTransactionPending = false;
3806 break;
3807 }
3808 }
3809 }
3810
chaviwca27f252018-02-06 16:46:39 -08003811 for (const DisplayState& display : displays) {
3812 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003813 }
3814
Marissa Walld600d572019-03-26 15:38:50 -07003815 // In case the client has sent a Transaction that should receive callbacks but without any
3816 // SurfaceControls that should be included in the callback, send the listener and callbackIds
3817 // to the callback thread so it can send an empty callback
3818 if (!listenerCallbacks.empty()) {
3819 mTransactionCompletedThread.run();
3820 }
3821 for (const auto& [listener, callbackIds] : listenerCallbacks) {
3822 mTransactionCompletedThread.addCallback(listener, callbackIds);
3823 }
3824
Marissa Walle2ffb422018-10-12 11:33:52 -07003825 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003826 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003827 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
3828 postTime, privileged);
3829 }
3830
Marissa Walle2ffb422018-10-12 11:33:52 -07003831 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07003832 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003833 mTransactionCompletedThread.sendCallbacks();
3834 }
3835 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003836
chaviw273171b2018-12-26 11:46:30 -08003837 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3838
Marissa Wall947d34e2019-03-29 14:03:53 -07003839 if (uncacheBuffer.isValid()) {
3840 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003841 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003842 }
3843
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003844 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3845 // anyway. This can be used as a flush mechanism for previous async transactions.
3846 // Empty animation transaction can be used to simulate back-pressure, so also force a
3847 // transaction for empty animation transactions.
3848 if (transactionFlags == 0 &&
3849 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003850 transactionFlags = eTransactionNeeded;
3851 }
3852
Marissa Wall06255332019-03-27 13:48:27 -07003853 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3854 // so we don't have to wake up again next frame to preform an uneeded traversal.
3855 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3856 transactionFlags = transactionFlags & (~eTraversalNeeded);
3857 mTraversalNeededMainThread = true;
3858 }
3859
Mathias Agopian386aa982011-11-07 21:58:03 -08003860 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003861 if (mInterceptor->isEnabled()) {
3862 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003863 }
Irvel468051e2016-06-13 16:44:44 -07003864
Mathias Agopian386aa982011-11-07 21:58:03 -08003865 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003866 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3867 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003868 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003869
3870 // if this is a synchronous transaction, wait for it to take effect
3871 // before returning.
3872 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003873 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003874 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003875 if (flags & eAnimation) {
3876 mAnimTransactionPending = true;
3877 }
chaviw4fe36852019-04-15 16:25:49 -07003878 if (mPendingInputWindowCommands.syncInputWindows) {
3879 mPendingSyncInputWindows = true;
3880 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003881
3882 // applyTransactionState can be called by either the main SF thread or by
3883 // another process through setTransactionState. While a given process may wish
3884 // to wait on synchronous transactions, the main SF thread should never
3885 // be blocked. Therefore, we only wait if isMainThread is false.
3886 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003887 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3888 if (CC_UNLIKELY(err != NO_ERROR)) {
3889 // just in case something goes wrong in SF, return to the
3890 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003891 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3892 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003893 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003894 break;
3895 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003896 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003897 }
3898}
3899
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003900uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3901 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3902 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003903
Mathias Agopiane57f2922012-08-09 16:29:12 -07003904 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003905 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3906
3907 const uint32_t what = s.what;
3908 if (what & DisplayState::eSurfaceChanged) {
3909 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3910 state.surface = s.surface;
3911 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003912 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003913 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003914 if (what & DisplayState::eLayerStackChanged) {
3915 if (state.layerStack != s.layerStack) {
3916 state.layerStack = s.layerStack;
3917 flags |= eDisplayTransactionNeeded;
3918 }
3919 }
3920 if (what & DisplayState::eDisplayProjectionChanged) {
3921 if (state.orientation != s.orientation) {
3922 state.orientation = s.orientation;
3923 flags |= eDisplayTransactionNeeded;
3924 }
3925 if (state.frame != s.frame) {
3926 state.frame = s.frame;
3927 flags |= eDisplayTransactionNeeded;
3928 }
3929 if (state.viewport != s.viewport) {
3930 state.viewport = s.viewport;
3931 flags |= eDisplayTransactionNeeded;
3932 }
3933 }
3934 if (what & DisplayState::eDisplaySizeChanged) {
3935 if (state.width != s.width) {
3936 state.width = s.width;
3937 flags |= eDisplayTransactionNeeded;
3938 }
3939 if (state.height != s.height) {
3940 state.height = s.height;
3941 flags |= eDisplayTransactionNeeded;
3942 }
3943 }
3944
Mathias Agopiane57f2922012-08-09 16:29:12 -07003945 return flags;
3946}
3947
Robert Carr14167e02019-02-13 13:50:55 -08003948bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003949 IPCThreadState* ipc = IPCThreadState::self();
3950 const int pid = ipc->getCallingPid();
3951 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003952 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003953 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003954 return false;
3955 }
3956 return true;
3957}
3958
Marissa Wall3dad52d2019-03-22 14:03:19 -07003959uint32_t SurfaceFlinger::setClientStateLocked(
3960 const ComposerState& composerState, int64_t desiredPresentTime,
3961 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3962 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003963 const layer_state_t& s = composerState.state;
3964 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3965
Mathias Agopian13127d82013-03-05 17:47:11 -08003966 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003967 if (layer == nullptr) {
3968 return 0;
3969 }
3970
chaviw8b3871a2017-11-01 17:41:01 -07003971 uint32_t flags = 0;
3972
Garfield Tan8a3083e2018-12-03 13:21:07 -08003973 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003974 bool geometryAppliesWithResize =
3975 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003976
3977 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3978 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003979 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003980 layer->pushPendingState();
3981 }
3982
chaviw8b3871a2017-11-01 17:41:01 -07003983 if (what & layer_state_t::ePositionChanged) {
3984 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3985 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003986 }
chaviw8b3871a2017-11-01 17:41:01 -07003987 }
3988 if (what & layer_state_t::eLayerChanged) {
3989 // NOTE: index needs to be calculated before we update the state
3990 const auto& p = layer->getParent();
3991 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003992 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003993 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003994 mCurrentState.layersSortedByZ.removeAt(idx);
3995 mCurrentState.layersSortedByZ.add(layer);
3996 // we need traversal (state changed)
3997 // AND transaction (list changed)
3998 flags |= eTransactionNeeded|eTraversalNeeded;
3999 }
chaviw8b3871a2017-11-01 17:41:01 -07004000 } else {
4001 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07004002 flags |= eTransactionNeeded|eTraversalNeeded;
4003 }
4004 }
chaviw8b3871a2017-11-01 17:41:01 -07004005 }
4006 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07004007 // NOTE: index needs to be calculated before we update the state
4008 const auto& p = layer->getParent();
4009 if (p == nullptr) {
4010 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4011 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
4012 mCurrentState.layersSortedByZ.removeAt(idx);
4013 mCurrentState.layersSortedByZ.add(layer);
4014 // we need traversal (state changed)
4015 // AND transaction (list changed)
4016 flags |= eTransactionNeeded|eTraversalNeeded;
4017 }
4018 } else {
4019 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
4020 flags |= eTransactionNeeded|eTraversalNeeded;
4021 }
chaviw8b3871a2017-11-01 17:41:01 -07004022 }
4023 }
4024 if (what & layer_state_t::eSizeChanged) {
4025 if (layer->setSize(s.w, s.h)) {
4026 flags |= eTraversalNeeded;
4027 }
4028 }
4029 if (what & layer_state_t::eAlphaChanged) {
4030 if (layer->setAlpha(s.alpha))
4031 flags |= eTraversalNeeded;
4032 }
4033 if (what & layer_state_t::eColorChanged) {
4034 if (layer->setColor(s.color))
4035 flags |= eTraversalNeeded;
4036 }
Peiyong Lind3788632018-09-18 16:01:31 -07004037 if (what & layer_state_t::eColorTransformChanged) {
4038 if (layer->setColorTransform(s.colorTransform)) {
4039 flags |= eTraversalNeeded;
4040 }
4041 }
Valerie Haudd0b7572019-01-29 14:59:27 -08004042 if (what & layer_state_t::eBackgroundColorChanged) {
4043 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
4044 flags |= eTraversalNeeded;
4045 }
4046 }
chaviw8b3871a2017-11-01 17:41:01 -07004047 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004048 // TODO: b/109894387
4049 //
4050 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
4051 // rotation. To see the problem observe that if we have a square parent, and a child
4052 // of the same size, then we rotate the child 45 degrees around it's center, the child
4053 // must now be cropped to a non rectangular 8 sided region.
4054 //
4055 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
4056 // private API, and the WindowManager only uses rotation in one case, which is on a top
4057 // level layer in which cropping is not an issue.
4058 //
4059 // However given that abuse of rotation matrices could lead to surfaces extending outside
4060 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
4061 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
4062 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08004063 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07004064 flags |= eTraversalNeeded;
4065 }
4066 if (what & layer_state_t::eTransparentRegionChanged) {
4067 if (layer->setTransparentRegionHint(s.transparentRegion))
4068 flags |= eTraversalNeeded;
4069 }
4070 if (what & layer_state_t::eFlagsChanged) {
4071 if (layer->setFlags(s.flags, s.mask))
4072 flags |= eTraversalNeeded;
4073 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004074 if (what & layer_state_t::eCropChanged_legacy) {
4075 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07004076 flags |= eTraversalNeeded;
4077 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07004078 if (what & layer_state_t::eCornerRadiusChanged) {
4079 if (layer->setCornerRadius(s.cornerRadius))
4080 flags |= eTraversalNeeded;
4081 }
chaviw8b3871a2017-11-01 17:41:01 -07004082 if (what & layer_state_t::eLayerStackChanged) {
4083 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
4084 // We only allow setting layer stacks for top level layers,
4085 // everything else inherits layer stack from its parent.
4086 if (layer->hasParent()) {
4087 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
4088 layer->getName().string());
4089 } else if (idx < 0) {
4090 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
4091 "that also does not appear in the top level layer list. Something"
4092 " has gone wrong.", layer->getName().string());
4093 } else if (layer->setLayerStack(s.layerStack)) {
4094 mCurrentState.layersSortedByZ.removeAt(idx);
4095 mCurrentState.layersSortedByZ.add(layer);
4096 // we need traversal (state changed)
4097 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07004098 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07004099 }
4100 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07004101 if (what & layer_state_t::eDeferTransaction_legacy) {
4102 if (s.barrierHandle_legacy != nullptr) {
4103 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
4104 } else if (s.barrierGbp_legacy != nullptr) {
4105 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07004106 if (authenticateSurfaceTextureLocked(gbp)) {
4107 const auto& otherLayer =
4108 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07004109 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07004110 } else {
4111 ALOGE("Attempt to defer transaction to to an"
4112 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08004113 }
4114 }
chaviw8b3871a2017-11-01 17:41:01 -07004115 // We don't trigger a traversal here because if no other state is
4116 // changed, we don't want this to cause any more work
4117 }
4118 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08004119 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07004120 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08004121 if (!hadParent) {
4122 mCurrentState.layersSortedByZ.remove(layer);
4123 }
chaviw8b3871a2017-11-01 17:41:01 -07004124 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08004125 }
chaviw8b3871a2017-11-01 17:41:01 -07004126 }
4127 if (what & layer_state_t::eReparentChildren) {
4128 if (layer->reparentChildren(s.reparentHandle)) {
4129 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07004130 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07004131 }
chaviw8b3871a2017-11-01 17:41:01 -07004132 if (what & layer_state_t::eDetachChildren) {
4133 layer->detachChildren();
4134 }
4135 if (what & layer_state_t::eOverrideScalingModeChanged) {
4136 layer->setOverrideScalingMode(s.overrideScalingMode);
4137 // 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 }
Marissa Wall61c58622018-07-18 10:12:20 -07004140 if (what & layer_state_t::eTransformChanged) {
4141 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
4142 }
4143 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
4144 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
4145 flags |= eTraversalNeeded;
4146 }
4147 if (what & layer_state_t::eCropChanged) {
4148 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
4149 }
Marissa Wall861616d2018-10-22 12:52:23 -07004150 if (what & layer_state_t::eFrameChanged) {
4151 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
4152 }
Marissa Wall61c58622018-07-18 10:12:20 -07004153 if (what & layer_state_t::eAcquireFenceChanged) {
4154 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
4155 }
4156 if (what & layer_state_t::eDataspaceChanged) {
4157 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
4158 }
4159 if (what & layer_state_t::eHdrMetadataChanged) {
4160 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
4161 }
4162 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
4163 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
4164 }
4165 if (what & layer_state_t::eApiChanged) {
4166 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
4167 }
4168 if (what & layer_state_t::eSidebandStreamChanged) {
4169 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
4170 }
Robert Carr720e5062018-07-30 17:45:14 -07004171 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08004172 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08004173 layer->setInputInfo(s.inputInfo);
4174 flags |= eTraversalNeeded;
4175 } else {
4176 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
4177 }
Robert Carr720e5062018-07-30 17:45:14 -07004178 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08004179 if (what & layer_state_t::eMetadataChanged) {
4180 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
4181 }
Peiyong Linc502cb72019-03-01 15:00:23 -08004182 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
4183 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
4184 flags |= eTraversalNeeded;
4185 }
4186 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004187 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07004188 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07004189 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07004190 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
4191 }
4192 }
Marissa Wall78b72202019-03-15 14:58:34 -07004193 bool bufferChanged = what & layer_state_t::eBufferChanged;
4194 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
4195 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004196 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07004197 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07004198 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
4199 if (success) {
4200 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
4201 success = ClientCache::getInstance()
4202 .registerErasedRecipient(s.cachedBuffer,
4203 wp<ClientCache::ErasedRecipient>(this));
4204 if (!success) {
4205 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
4206 }
4207 }
Marissa Wall78b72202019-03-15 14:58:34 -07004208 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004209 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07004210 } else if (bufferChanged) {
4211 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08004212 }
Marissa Wall78b72202019-03-15 14:58:34 -07004213 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07004214 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08004215 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08004216 }
Marissa Wallebc2c052019-01-16 19:16:55 -08004217 }
Marissa Walle2ffb422018-10-12 11:33:52 -07004218 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
4219 // Do not put anything that updates layer state or modifies flags after
4220 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07004221 return flags;
4222}
4223
chaviw273171b2018-12-26 11:46:30 -08004224uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
4225 uint32_t flags = 0;
4226 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
4227 flags |= eTraversalNeeded;
4228 }
4229
chaviwa911b102019-02-14 10:18:33 -08004230 if (inputWindowCommands.syncInputWindows) {
4231 flags |= eTraversalNeeded;
4232 }
4233
Vishnu Nairec0ab382019-02-13 15:32:56 -08004234 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08004235 return flags;
4236}
4237
Marissa Wall2d814fb2019-04-09 18:52:57 +00004238status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
4239 uint32_t h, PixelFormat format, uint32_t flags,
4240 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07004241 sp<IGraphicBufferProducer>* gbp,
4242 const sp<IBinder>& parentHandle,
4243 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004244 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07004245 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004246 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004247 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07004248 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07004249
Robert Carrc0df3122019-04-11 13:18:21 -07004250 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
4251 "Expected only one of parentLayer or parentHandle to be non-null. "
4252 "Programmer error?");
4253
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004254 status_t result = NO_ERROR;
4255
4256 sp<Layer> layer;
4257
Cody Northropbc755282017-03-31 12:00:08 -06004258 String8 uniqueName = getUniqueLayerName(name);
4259
Evan Roskya1f1e152019-01-24 16:17:46 -08004260 bool primaryDisplayOnly = false;
4261
4262 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
4263 // TODO b/64227542
4264 if (metadata.has(METADATA_WINDOW_TYPE)) {
4265 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
4266 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07004267 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08004268 primaryDisplayOnly = true;
4269 }
4270 }
4271
Mathias Agopian3165cc22012-08-08 19:42:09 -07004272 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07004273 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08004274 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
4275 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07004276
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004277 break;
Marissa Wall61c58622018-07-18 10:12:20 -07004278 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08004279 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
4280 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07004281 break;
chaviw13fdc492017-06-27 12:40:18 -07004282 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004283 // check if buffer size is set for color layer.
4284 if (w > 0 || h > 0) {
4285 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
4286 int(w), int(h));
4287 return BAD_VALUE;
4288 }
4289
Evan Roskya1f1e152019-01-24 16:17:46 -08004290 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
4291 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004292 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07004293 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08004294 // check if buffer size is set for container layer.
4295 if (w > 0 || h > 0) {
4296 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
4297 int(w), int(h));
4298 return BAD_VALUE;
4299 }
Evan Roskya1f1e152019-01-24 16:17:46 -08004300 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
4301 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07004302 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004303 default:
4304 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004305 break;
4306 }
4307
Dan Stoza7d89d062015-04-30 13:29:25 -07004308 if (result != NO_ERROR) {
4309 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004310 }
Dan Stoza7d89d062015-04-30 13:29:25 -07004311
Evan Roskya1f1e152019-01-24 16:17:46 -08004312 if (primaryDisplayOnly) {
4313 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07004314 }
4315
Robert Carrb89ea9d2018-12-10 13:01:14 -08004316 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07004317 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
4318 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07004319 if (result != NO_ERROR) {
4320 return result;
4321 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08004322 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07004323
4324 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004325 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004326}
4327
Cody Northropbc755282017-03-31 12:00:08 -06004328String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
4329{
4330 bool matchFound = true;
4331 uint32_t dupeCounter = 0;
4332
4333 // Tack on our counter whether there is a hit or not, so everyone gets a tag
4334 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
4335
Dan Stoza436ccf32018-06-21 12:10:12 -07004336 // Grab the state lock since we're accessing mCurrentState
4337 Mutex::Autolock lock(mStateLock);
4338
Cody Northropbc755282017-03-31 12:00:08 -06004339 // Loop over layers until we're sure there is no matching name
4340 while (matchFound) {
4341 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07004342 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06004343 if (layer->getName() == uniqueName) {
4344 matchFound = true;
4345 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
4346 }
4347 });
4348 }
4349
Marissa Wallf1de4bd2018-05-22 13:05:01 -07004350 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
4351 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06004352
4353 return uniqueName;
4354}
4355
Marissa Wallfd668622018-05-10 10:21:13 -07004356status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
4357 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004358 LayerMetadata metadata, PixelFormat& format,
4359 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004360 sp<IGraphicBufferProducer>* gbp,
4361 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004362 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004363 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004364 case PIXEL_FORMAT_TRANSPARENT:
4365 case PIXEL_FORMAT_TRANSLUCENT:
4366 format = PIXEL_FORMAT_RGBA_8888;
4367 break;
4368 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004369 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004370 break;
4371 }
4372
Evan Roskya1f1e152019-01-24 16:17:46 -08004373 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
4374 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07004375 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004376 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004377 *handle = layer->getHandle();
4378 *gbp = layer->getProducer();
4379 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004380 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004381
Marissa Wallfd668622018-05-10 10:21:13 -07004382 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004383 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004384}
4385
Marissa Wall61c58622018-07-18 10:12:20 -07004386status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
4387 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004388 LayerMetadata metadata, sp<IBinder>* handle,
4389 sp<Layer>* outLayer) {
4390 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
4391 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07004392 *handle = layer->getHandle();
4393 *outLayer = layer;
4394
4395 return NO_ERROR;
4396}
4397
Evan Roskya1f1e152019-01-24 16:17:46 -08004398status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
4399 uint32_t h, uint32_t flags, LayerMetadata metadata,
4400 sp<IBinder>* handle, sp<Layer>* outLayer) {
4401 *outLayer = getFactory().createColorLayer(
4402 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004403 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004404 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004405}
4406
Evan Roskya1f1e152019-01-24 16:17:46 -08004407status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
4408 uint32_t w, uint32_t h, uint32_t flags,
4409 LayerMetadata metadata, sp<IBinder>* handle,
4410 sp<Layer>* outLayer) {
4411 *outLayer = getFactory().createContainerLayer(
4412 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07004413 *handle = (*outLayer)->getHandle();
4414 return NO_ERROR;
4415}
4416
4417
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004418void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004419 mLayersPendingRemoval.add(layer);
4420 mLayersRemoved = true;
4421 setTransactionFlags(eTransactionNeeded);
4422}
4423
Robert Carr695d5282018-12-18 15:27:58 -08004424void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004425{
Robert Carr2e102c92018-10-23 12:11:15 -07004426 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004427 // If a layer has a parent, we allow it to out-live it's handle
4428 // with the idea that the parent holds a reference and will eventually
4429 // be cleaned up. However no one cleans up the top-level so we do so
4430 // here.
4431 if (layer->getParent() == nullptr) {
4432 mCurrentState.layersSortedByZ.remove(layer);
4433 }
4434 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004435
4436 auto it = mLayersByLocalBinderToken.begin();
4437 while (it != mLayersByLocalBinderToken.end()) {
4438 if (it->second == layer) {
4439 it = mLayersByLocalBinderToken.erase(it);
4440 } else {
4441 it++;
4442 }
4443 }
4444
Robert Carr695d5282018-12-18 15:27:58 -08004445 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004446}
4447
Mathias Agopianb60314a2012-04-10 22:09:54 -07004448// ---------------------------------------------------------------------------
4449
Andy McFadden13a082e2012-08-24 10:16:42 -07004450void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004451 const auto display = getDefaultDisplayDeviceLocked();
4452 if (!display) return;
4453
4454 const sp<IBinder> token = display->getDisplayToken().promote();
4455 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004456
Jesse Hall01e29052013-02-19 16:13:35 -08004457 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004458 Vector<ComposerState> state;
4459 Vector<DisplayState> displays;
4460 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004461 d.what = DisplayState::eDisplayProjectionChanged |
4462 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004463 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004464 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004465 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004466 d.frame.makeInvalid();
4467 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004468 d.width = 0;
4469 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004470 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07004471 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004472
Dominik Laskowskie9774092018-12-11 10:04:24 -08004473 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004474
Dominik Laskowski83b88212018-12-11 13:34:06 -08004475 const nsecs_t vsyncPeriod = getVsyncPeriod();
4476 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004477
Brian Andersond0010582017-03-07 13:20:31 -08004478 // Use phase of 0 since phase is not known.
4479 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004480 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004481 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004482}
4483
4484void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004485 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004486 postMessageAsync(
4487 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004488}
4489
Ady Abraham27c70212019-06-11 10:52:26 -07004490void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4491 if (mHWCVsyncState != enabled) {
4492 getHwComposer().setVsyncEnabled(displayId, enabled);
4493 mHWCVsyncState = enabled;
4494 }
4495}
4496
Dominik Laskowskie9774092018-12-11 10:04:24 -08004497void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004498 if (display->isVirtual()) {
4499 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004500 return;
4501 }
4502
Dominik Laskowski075d3172018-05-24 15:50:06 -07004503 const auto displayId = display->getId();
4504 LOG_ALWAYS_FATAL_IF(!displayId);
4505
Dominik Laskowski34157762018-10-31 13:07:19 -07004506 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004507
4508 int currentMode = display->getPowerMode();
4509 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004510 return;
4511 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004512
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004513 display->setPowerMode(mode);
4514
Lloyd Pique4dccc412018-01-22 17:21:36 -08004515 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004516 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004517 }
4518
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004519 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004520 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004521 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004522 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004523 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004524 mScheduler->onScreenAcquired(mAppConnectionHandle);
4525 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004526 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004528 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004529 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004530 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004531
4532 struct sched_param param = {0};
4533 param.sched_priority = 1;
4534 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4535 ALOGW("Couldn't set SCHED_FIFO on display on");
4536 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004537 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004538 // Turn off the display
4539 struct sched_param param = {0};
4540 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4541 ALOGW("Couldn't set SCHED_OTHER on display off");
4542 }
4543
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004544 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004545 mScheduler->disableHardwareVsync(true);
4546 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004547 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004548
Ady Abraham27c70212019-06-11 10:52:26 -07004549 // Make sure HWVsync is disabled before turning off the display
4550 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4551
Dominik Laskowski075d3172018-05-24 15:50:06 -07004552 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004553 mVisibleRegionsDirty = true;
4554 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004555 } else if (mode == HWC_POWER_MODE_DOZE ||
4556 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004557 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004558 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004559 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004560 mScheduler->onScreenAcquired(mAppConnectionHandle);
4561 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004562 }
4563 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4564 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004565 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004566 mScheduler->disableHardwareVsync(true);
4567 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004568 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004569 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004570 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004571 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004572 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004573 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004574
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004575 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004576 mTimeStats->setPowerMode(mode);
Dominik Laskowski22488f62019-03-28 09:53:04 -07004577 mRefreshRateStats.setPowerMode(mode);
Ady Abraham24363172019-07-12 12:37:57 -07004578 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004579 }
4580
Dominik Laskowski34157762018-10-31 13:07:19 -07004581 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004582}
4583
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004584void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004585 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004586 const auto display = getDisplayDevice(displayToken);
4587 if (!display) {
4588 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4589 displayToken.get());
4590 } else if (display->isVirtual()) {
4591 ALOGW("Attempt to set power mode %d for virtual display", mode);
4592 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004593 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004594 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004595 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004596}
4597
4598// ---------------------------------------------------------------------------
4599
Dominik Laskowskic2867142019-01-21 11:33:38 -08004600status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4601 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004602 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004603
Mathias Agopianbd115332013-04-18 16:41:04 -07004604 IPCThreadState* ipc = IPCThreadState::self();
4605 const int pid = ipc->getCallingPid();
4606 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004607
Mathias Agopianbd115332013-04-18 16:41:04 -07004608 if ((uid != AID_SHELL) &&
4609 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004610 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4611 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004612 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004613 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004614 // (this would indicate SF is stuck, but we want to be able to
4615 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004616 status_t err = mStateLock.timedLock(s2ns(1));
4617 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004618 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004619 StringAppendF(&result,
4620 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4621 "(no locks held)\n",
4622 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004623 }
4624
Dominik Laskowskic2867142019-01-21 11:33:38 -08004625 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07004626
Dominik Laskowskic2867142019-01-21 11:33:38 -08004627 static const std::unordered_map<std::string, Dumper> dumpers = {
4628 {"--clear-layer-stats"s, dumper([this](std::string&) { mLayerStats.clear(); })},
4629 {"--disable-layer-stats"s, dumper([this](std::string&) { mLayerStats.disable(); })},
4630 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Ady Abraham3aff9172019-02-07 19:10:26 -08004631 {"--dispsync"s, dumper([this](std::string& s) {
Ady Abraham3aff9172019-02-07 19:10:26 -08004632 mScheduler->dumpPrimaryDispSync(s);
Ady Abraham3aff9172019-02-07 19:10:26 -08004633 })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004634 {"--dump-layer-stats"s, dumper([this](std::string& s) { mLayerStats.dump(s); })},
4635 {"--enable-layer-stats"s, dumper([this](std::string&) { mLayerStats.enable(); })},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004636 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4637 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4638 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4639 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4640 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4641 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004642 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004643 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4644 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004645
Dominik Laskowskic2867142019-01-21 11:33:38 -08004646 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004647
Dominik Laskowskic2867142019-01-21 11:33:38 -08004648 if (const auto it = dumpers.find(flag); it != dumpers.end()) {
4649 (it->second)(args, asProto, result);
4650 } else {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004651 if (asProto) {
4652 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4653 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4654 } else {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004655 dumpAllLocked(args, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004656 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004657 }
4658
Mathias Agopian9795c422009-08-26 16:36:26 -07004659 if (locked) {
4660 mStateLock.unlock();
4661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004664 return NO_ERROR;
4665}
4666
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004667status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4668 if (asProto && mTracing.isEnabled()) {
4669 mTracing.writeToFileAsync();
4670 }
4671
4672 return doDump(fd, DumpArgs(), asProto);
4673}
4674
Dominik Laskowskic2867142019-01-21 11:33:38 -08004675void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004676 mCurrentState.traverseInZOrder(
4677 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004678}
4679
Dominik Laskowskic2867142019-01-21 11:33:38 -08004680void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004681 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004682
Dominik Laskowskic2867142019-01-21 11:33:38 -08004683 if (args.size() > 1) {
4684 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004685 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004686 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004687 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004688 }
Robert Carr2047fae2016-11-28 14:09:09 -08004689 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004690 } else {
4691 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692 }
4693}
4694
Dominik Laskowskic2867142019-01-21 11:33:38 -08004695void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08004696 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004697 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004698 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004699 }
Robert Carr2047fae2016-11-28 14:09:09 -08004700 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004701
Svetoslavd85084b2014-03-20 10:28:31 -07004702 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004703}
4704
Dominik Laskowskic2867142019-01-21 11:33:38 -08004705void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4706 mTimeStats->parseArgs(asProto, args, result);
4707}
4708
Jamie Gennis6547ff42013-07-16 20:12:42 -07004709// This should only be called from the main thread. Otherwise it would need
4710// the lock and should use mCurrentState rather than mDrawingState.
4711void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004712 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004713 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004714 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004715
4716 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4717}
4718
Yiwei Zhang5434a782018-12-05 18:06:32 -08004719void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004720 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004721
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004722 if (isLayerTripleBufferingDisabled())
4723 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004724
Yiwei Zhang5434a782018-12-05 18:06:32 -08004725 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4726 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4727 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4728 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4729 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4730 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004731 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004732}
4733
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004734void SurfaceFlinger::dumpVSync(std::string& result) const {
Ana Krulec757f63a2019-01-25 10:46:18 -08004735 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004736 StringAppendF(&result,
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004737 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004738 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004739
Ady Abraham97d04232019-03-05 19:48:12 -08004740 StringAppendF(&result, "Scheduler enabled.");
Ana Krulecba13ab32019-02-20 14:14:12 -08004741 StringAppendF(&result, "+ Smart 90 for video detection: %s\n\n",
4742 mUseSmart90ForVideo ? "on" : "off");
Ady Abraham42b3beb2019-07-09 18:09:52 -07004743 StringAppendF(&result, "Allowed Display Configs: ");
4744 for (int32_t configId : mAllowedDisplayConfigs) {
4745 for (auto refresh : mRefreshRateConfigs.getRefreshRates()) {
4746 if (refresh.second && refresh.second->configId == configId) {
4747 StringAppendF(&result, "%dHz, ", refresh.second->fps);
4748 }
4749 }
4750 }
4751 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4752 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Ana Krulecc2870422019-01-29 19:00:58 -08004753 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004754}
4755
Yiwei Zhang5434a782018-12-05 18:06:32 -08004756void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4757 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004758 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4759 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004760 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004761 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004762 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004763 }
David Sodman4a36e932017-11-07 14:29:47 -08004764 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004765 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004766 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004767 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4768 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004769}
4770
Dan Stozae77c7662016-05-13 11:37:28 -07004771void SurfaceFlinger::recordBufferingStats(const char* layerName,
4772 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004773 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4774 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004775 for (const auto& segment : history) {
4776 if (!segment.usedThirdBuffer) {
4777 stats.twoBufferTime += segment.totalTime;
4778 }
4779 if (segment.occupancyAverage < 1.0f) {
4780 stats.doubleBufferedTime += segment.totalTime;
4781 } else if (segment.occupancyAverage < 2.0f) {
4782 stats.tripleBufferedTime += segment.totalTime;
4783 }
4784 ++stats.numSegments;
4785 stats.totalTime += segment.totalTime;
4786 }
4787}
4788
Yiwei Zhang5434a782018-12-05 18:06:32 -08004789void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4790 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004791
4792 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4793 const size_t count = currentLayers.size();
4794 for (size_t i=0 ; i<count ; i++) {
4795 currentLayers[i]->dumpFrameEvents(result);
4796 }
4797}
4798
Yiwei Zhang5434a782018-12-05 18:06:32 -08004799void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004800 result.append("Buffering stats:\n");
4801 result.append(" [Layer name] <Active time> <Two buffer> "
4802 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004803 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004804 typedef std::tuple<std::string, float, float, float> BufferTuple;
4805 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004806 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004807 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004808 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004809 if (stats.numSegments == 0) {
4810 continue;
4811 }
4812 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4813 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4814 stats.totalTime;
4815 float doubleBufferRatio = static_cast<float>(
4816 stats.doubleBufferedTime) / stats.totalTime;
4817 float tripleBufferRatio = static_cast<float>(
4818 stats.tripleBufferedTime) / stats.totalTime;
4819 sorted.insert({activeTime, {name, twoBufferRatio,
4820 doubleBufferRatio, tripleBufferRatio}});
4821 }
4822 for (const auto& sortedPair : sorted) {
4823 float activeTime = sortedPair.first;
4824 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004825 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4826 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004827 }
4828 result.append("\n");
4829}
4830
Yiwei Zhang5434a782018-12-05 18:06:32 -08004831void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004832 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004833 const auto displayId = display->getId();
4834 if (!displayId) {
4835 continue;
4836 }
4837 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004838 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004839 continue;
4840 }
4841
Yiwei Zhang5434a782018-12-05 18:06:32 -08004842 StringAppendF(&result,
4843 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4844 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004845 uint8_t port;
4846 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004847 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004848 result.append("no identification data\n");
4849 continue;
4850 }
4851
4852 if (!isEdid(data)) {
4853 result.append("unknown identification data: ");
4854 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004855 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004856 }
4857 result.append("\n");
4858 continue;
4859 }
4860
4861 const auto edid = parseEdid(data);
4862 if (!edid) {
4863 result.append("invalid EDID: ");
4864 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004865 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004866 }
4867 result.append("\n");
4868 continue;
4869 }
4870
Yiwei Zhang5434a782018-12-05 18:06:32 -08004871 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004872 result.append(edid->displayName.data(), edid->displayName.length());
4873 result.append("\"\n");
4874 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004875}
4876
Yiwei Zhang5434a782018-12-05 18:06:32 -08004877void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004878 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004879 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4880 StringAppendF(&result, "DisplayColorSetting: %s\n",
4881 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004882
4883 // TODO: print out if wide-color mode is active or not
4884
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004885 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004886 const auto displayId = display->getId();
4887 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004888 continue;
4889 }
4890
Yiwei Zhang5434a782018-12-05 18:06:32 -08004891 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004892 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004893 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004894 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004895 }
4896
Lloyd Pique32cbe282018-10-19 13:09:22 -07004897 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004898 StringAppendF(&result, " Current color mode: %s (%d)\n",
4899 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004900 }
4901 result.append("\n");
4902}
4903
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004904LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet,
4905 uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004906 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004907 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4908 const State& state = useDrawing ? mDrawingState : mCurrentState;
4909 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004910 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004911 layer->writeToProto(layerProto, stateSet, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004912 });
4913
4914 return layersProto;
4915}
4916
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004917LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(
4918 const sp<DisplayDevice>& displayDevice) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004919 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004920
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004921 SizeProto* resolution = layersProto.mutable_resolution();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004922 resolution->set_w(displayDevice->getWidth());
4923 resolution->set_h(displayDevice->getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004924
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004925 auto display = displayDevice->getCompositionDisplay();
Lloyd Pique32cbe282018-10-19 13:09:22 -07004926 const auto& displayState = display->getState();
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004927
Lloyd Pique32cbe282018-10-19 13:09:22 -07004928 layersProto.set_color_mode(decodeColorMode(displayState.colorMode));
4929 layersProto.set_color_transform(decodeColorTransform(displayState.colorTransform));
4930 layersProto.set_global_transform(displayState.orientation);
4931
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004932 const auto displayId = displayDevice->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004933 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004934 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004935 if (!layer->visibleRegion.isEmpty() && !display->getOutputLayersOrderedByZ().empty()) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004936 LayerProto* layerProto = layersProto.add_layers();
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004937 layer->writeToProto(layerProto, displayDevice);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004938 }
4939 });
4940
4941 return layersProto;
4942}
4943
Dominik Laskowskic2867142019-01-21 11:33:38 -08004944void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4945 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004946 Colorizer colorizer(colorize);
4947
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004948 // figure out if we're stuck somewhere
4949 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004950 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004951 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4952
4953 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004954 * Dump library configuration.
4955 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004956
4957 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004958 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004959 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004960 appendSfConfigString(result);
4961 appendUiConfigString(result);
4962 appendGuiConfigString(result);
4963 result.append("\n");
4964
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004965 result.append("\nDisplay identification data:\n");
4966 dumpDisplayIdentificationData(result);
4967
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004968 result.append("\nWide-Color information:\n");
4969 dumpWideColorInfo(result);
4970
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004971 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004972 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004973 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004974 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004975 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004976
Andy McFadden41d67d72014-04-25 16:58:34 -07004977 colorizer.bold(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004978 result.append("VSYNC configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004979 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004980 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004981 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004982
Dan Stozab90cf072015-03-05 11:05:59 -08004983 dumpStaticScreenStats(result);
4984 result.append("\n");
4985
Alec Mouri40189b02019-03-05 15:07:54 -08004986 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4987 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4988 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004989
Dan Stozae77c7662016-05-13 11:37:28 -07004990 dumpBufferingStats(result);
4991
Andy McFadden4803b742012-09-24 19:07:20 -07004992 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004993 * Dump the visible layer list
4994 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004995 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004996 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4997 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4998 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004999 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07005000
Chia-I Wu2f884132018-09-13 15:17:58 -07005001 {
5002 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
5003 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005004 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07005005 result.append("\n");
5006 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005007
Lloyd Pique207def92019-02-28 16:09:52 -08005008 {
5009 StringAppendF(&result, "Composition layers\n");
5010 mDrawingState.traverseInZOrder([&](Layer* layer) {
5011 auto compositionLayer = layer->getCompositionLayer();
5012 if (compositionLayer) compositionLayer->dump(result);
5013 });
5014 }
5015
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005016 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005017 * Dump Display state
5018 */
5019
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005020 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005021 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005022 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005023 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005024 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005025 }
Chia-I Wu1e043612018-03-01 09:45:09 -08005026 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07005027
5028 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005029 * Dump SurfaceFlinger global state
5030 */
5031
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005032 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005033 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005034 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005035
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07005036 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005037
Ady Abrahama3b08ef2019-07-15 18:43:10 -07005038 DebugEGLImageTracker::getInstance()->dump(result);
5039
Dominik Laskowski075d3172018-05-24 15:50:06 -07005040 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07005041 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
5042 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005043 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
5044 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08005045 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08005046 StringAppendF(&result,
5047 " transaction-flags : %08x\n"
5048 " gpu_to_cpu_unsupported : %d\n",
5049 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005050
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005051 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07005052 displayId && getHwComposer().isConnected(*displayId)) {
5053 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08005054 StringAppendF(&result,
5055 " refresh-rate : %f fps\n"
5056 " x-dpi : %f\n"
5057 " y-dpi : %f\n",
5058 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
5059 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005060 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005061
Yiwei Zhang5434a782018-12-05 18:06:32 -08005062 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005063
Dan Stozae22aec72016-08-01 13:20:59 -07005064 /*
Yichi Chenadc69612018-09-15 14:51:18 +08005065 * Tracing state
5066 */
5067 mTracing.dump(result);
5068 result.append("\n");
5069
5070 /*
Dan Stozae22aec72016-08-01 13:20:59 -07005071 * HWC layer minidump
5072 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005073 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07005074 const auto displayId = display->getId();
5075 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07005076 continue;
5077 }
5078
Yiwei Zhang5434a782018-12-05 18:06:32 -08005079 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07005080 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005081 const sp<DisplayDevice> displayDevice = display;
5082 mCurrentState.traverseInZOrder(
5083 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07005084 result.append("\n");
5085 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005086
5087 /*
5088 * Dump HWComposer state
5089 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005090 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02005091 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02005092 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005093 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08005094 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07005095 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005096
5097 /*
5098 * Dump gralloc state
5099 */
5100 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
5101 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005102
5103 /*
5104 * Dump VrFlinger state if in use.
5105 */
5106 if (mVrFlingerRequestsDisplay && mVrFlinger) {
5107 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08005108 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07005109 result.append("\n");
5110 }
Ana Krulecb43429d2019-01-09 14:28:51 -08005111
5112 /**
5113 * Scheduler dump state.
5114 */
Ana Krulecc2870422019-01-29 19:00:58 -08005115 result.append("\nScheduler state:\n");
5116 result.append(mScheduler->doDump() + "\n");
Ana Krulecfefd6ae2019-02-13 17:53:08 -08005117 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
Dominik Laskowski22488f62019-03-28 09:53:04 -07005118 result.append(mRefreshRateStats.doDump() + "\n");
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07005119
5120 result.append(mTimeStats->miniDump());
5121 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08005122}
5123
Dominik Laskowski075d3172018-05-24 15:50:06 -07005124const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07005125 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07005126 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07005127 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005128 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07005129 }
5130 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005131
Dominik Laskowski34157762018-10-31 13:07:19 -07005132 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005133 static const Vector<sp<Layer>> empty;
5134 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07005135}
5136
Chia-I Wu28f320b2018-05-03 11:02:56 -07005137void SurfaceFlinger::updateColorMatrixLocked() {
5138 mat4 colorMatrix;
5139 if (mGlobalSaturationFactor != 1.0f) {
5140 // Rec.709 luma coefficients
5141 float3 luminance{0.213f, 0.715f, 0.072f};
5142 luminance *= 1.0f - mGlobalSaturationFactor;
5143 mat4 saturationMatrix = mat4(
5144 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
5145 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
5146 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
5147 vec4{0.0f, 0.0f, 0.0f, 1.0f}
5148 );
5149 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
5150 } else {
5151 colorMatrix = mClientColorMatrix * mDaltonizer();
5152 }
5153
5154 if (mCurrentState.colorMatrix != colorMatrix) {
5155 mCurrentState.colorMatrix = colorMatrix;
5156 mCurrentState.colorMatrixChanged = true;
5157 setTransactionFlags(eTransactionNeeded);
5158 }
5159}
5160
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005161status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005162#pragma clang diagnostic push
5163#pragma clang diagnostic error "-Wswitch-enum"
5164 switch (static_cast<ISurfaceComposerTag>(code)) {
5165 // These methods should at minimum make sure that the client requested
5166 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00005167 case BOOT_FINISHED:
5168 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005169 case CREATE_DISPLAY:
5170 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00005171 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005172 case GET_ANIMATION_FRAME_STATS:
5173 case GET_HDR_CAPABILITIES:
5174 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08005175 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005176 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005177 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07005178 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07005179 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08005180 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07005181 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07005182 case GET_DISPLAYED_CONTENT_SAMPLE:
5183 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07005184 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
5185 IPCThreadState* ipc = IPCThreadState::self();
5186 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
5187 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07005188 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005189 }
Robert Carr1db73f62016-12-21 12:58:51 -08005190 return OK;
5191 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005192 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005193 IPCThreadState* ipc = IPCThreadState::self();
5194 const int pid = ipc->getCallingPid();
5195 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00005196 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
5197 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005198 return PERMISSION_DENIED;
5199 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005200 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005201 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005202 // Used by apps to hook Choreographer to SurfaceFlinger.
5203 case CREATE_DISPLAY_EVENT_CONNECTION:
5204 // The following calls are currently used by clients that do not
5205 // request necessary permissions. However, they do not expose any secret
5206 // information, so it is OK to pass them.
5207 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07005208 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005209 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08005210 case GET_PHYSICAL_DISPLAY_IDS:
5211 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005212 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08005213 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00005214 case GET_DISPLAY_CONFIGS:
5215 case GET_DISPLAY_STATS:
5216 case GET_SUPPORTED_FRAME_TIMESTAMPS:
5217 // Calling setTransactionState is safe, because you need to have been
5218 // granted a reference to Client* and Handle* to do anything with it.
5219 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08005220 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07005221 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08005222 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08005223 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00005224 case IS_WIDE_COLOR_DISPLAY:
5225 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
5226 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005227 return OK;
5228 }
5229 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08005230 case CAPTURE_SCREEN:
5231 case ADD_REGION_SAMPLING_LISTENER:
5232 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005233 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07005234 IPCThreadState* ipc = IPCThreadState::self();
5235 const int pid = ipc->getCallingPid();
5236 const int uid = ipc->getCallingUid();
5237 if ((uid != AID_GRAPHICS) &&
5238 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
5239 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
5240 return PERMISSION_DENIED;
5241 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005242 return OK;
5243 }
5244 // The following codes are deprecated and should never be allowed to access SF.
5245 case CONNECT_DISPLAY_UNUSED:
5246 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
5247 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
5248 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07005249 }
chaviw93df2ea2019-04-30 16:45:12 -07005250 case CAPTURE_SCREEN_BY_ID: {
5251 IPCThreadState* ipc = IPCThreadState::self();
5252 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07005253 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07005254 return OK;
5255 }
5256 return PERMISSION_DENIED;
5257 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005258 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00005259
5260 // These codes are used for the IBinder protocol to either interrogate the recipient
5261 // side of the transaction for its canonical interface descriptor or to dump its state.
5262 // We let them pass by default.
5263 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
5264 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
5265 code == IBinder::SYSPROPS_TRANSACTION) {
5266 return OK;
5267 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005268 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00005269 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07005270 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00005271 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
5272 return OK;
5273 }
5274 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
5275 return PERMISSION_DENIED;
5276#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005277}
5278
Ana Krulec13be8ad2018-08-21 02:43:56 +00005279status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
5280 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07005281 status_t credentialCheck = CheckTransactCodeCredentials(code);
5282 if (credentialCheck != OK) {
5283 return credentialCheck;
5284 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005285
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005286 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
5287 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07005288 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07005289 IPCThreadState* ipc = IPCThreadState::self();
5290 const int uid = ipc->getCallingUid();
5291 if (CC_UNLIKELY(uid != AID_SYSTEM
5292 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07005293 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00005294 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07005295 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005296 return PERMISSION_DENIED;
5297 }
5298 int n;
5299 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07005300 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07005301 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005302 return NO_ERROR;
5303 case 1002: // SHOW_UPDATES
5304 n = data.readInt32();
5305 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07005306 invalidateHwcGeometry();
5307 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005308 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005309 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07005310 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005311 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005312 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005313 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07005314 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07005315 setTransactionFlags(
5316 eTransactionNeeded|
5317 eDisplayTransactionNeeded|
5318 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07005319 return NO_ERROR;
5320 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08005321 case 1006:{ // send empty update
5322 signalRefresh();
5323 return NO_ERROR;
5324 }
Mathias Agopian53331da2011-08-22 21:44:41 -07005325 case 1008: // toggle use of hw composer
5326 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005327 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07005328 invalidateHwcGeometry();
5329 repaintEverything();
5330 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005331 case 1009: // toggle use of transform hint
5332 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005333 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005334 invalidateHwcGeometry();
5335 repaintEverything();
5336 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005337 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005338 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005339 reply->writeInt32(0);
5340 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005341 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005342 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005343 return NO_ERROR;
5344 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005345 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005346 if (!display) {
5347 return NAME_NOT_FOUND;
5348 }
5349
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005350 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005351 return NO_ERROR;
5352 }
5353 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005354 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005355 // daltonize
5356 n = data.readInt32();
5357 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005358 case 1:
5359 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5360 break;
5361 case 2:
5362 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5363 break;
5364 case 3:
5365 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5366 break;
5367 default:
5368 mDaltonizer.setType(ColorBlindnessType::None);
5369 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005370 }
5371 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005372 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005373 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005374 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005375 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005376
5377 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005378 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005379 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005380 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005381 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005382 // apply a color matrix
5383 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005384 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005385 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005386 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005387 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005388 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005389 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005390 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005391 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005392 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005393 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005394
5395 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5396 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005397 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005398 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5399 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5400 }
5401
Chia-I Wu28f320b2018-05-03 11:02:56 -07005402 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005403 return NO_ERROR;
5404 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005405 // This is an experimental interface
5406 // Needs to be shifted to proper binder interface when we productize
5407 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005408 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005409 // TODO(b/113612090): Evaluate if this can be removed.
Ana Krulecc2870422019-01-29 19:00:58 -08005410 mScheduler->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005411 return NO_ERROR;
5412 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005413 case 1017: {
5414 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005415 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005416 return NO_ERROR;
5417 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005418 case 1018: { // Modify Choreographer's phase offset
5419 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005420 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005421 return NO_ERROR;
5422 }
5423 case 1019: { // Modify SurfaceFlinger's phase offset
5424 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005425 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005426 return NO_ERROR;
5427 }
Irvel468051e2016-06-13 16:44:44 -07005428 case 1020: { // Layer updates interceptor
5429 n = data.readInt32();
5430 if (n) {
5431 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005432 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005433 }
5434 else{
5435 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005436 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005437 }
5438 return NO_ERROR;
5439 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005440 case 1021: { // Disable HWC virtual displays
5441 n = data.readInt32();
5442 mUseHwcVirtualDisplays = !n;
5443 return NO_ERROR;
5444 }
Romain Guy0147a172017-06-01 13:53:56 -07005445 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005446 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005447 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005448
Chia-I Wu28f320b2018-05-03 11:02:56 -07005449 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005450 return NO_ERROR;
5451 }
Romain Guy54f154a2017-10-24 21:40:32 +01005452 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005453 int32_t colorMode;
5454
Chia-I Wu0d711262018-05-21 15:19:35 -07005455 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005456 if (data.readInt32(&colorMode) == NO_ERROR) {
5457 mForceColorMode = static_cast<ColorMode>(colorMode);
5458 }
Romain Guy54f154a2017-10-24 21:40:32 +01005459 invalidateHwcGeometry();
5460 repaintEverything();
5461 return NO_ERROR;
5462 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005463 // Deprecate, use 1030 to check whether the device is color managed.
5464 case 1024: {
5465 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005466 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005467 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005468 n = data.readInt32();
5469 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005470 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005471 Mutex::Autolock lock(mStateLock);
5472 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005473 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005474 reply->writeInt32(NO_ERROR);
5475 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005476 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005477 bool writeFile = false;
5478 {
5479 Mutex::Autolock lock(mStateLock);
5480 mTracingEnabledChanged = true;
5481 writeFile = mTracing.disable();
5482 }
5483
5484 if (writeFile) {
5485 reply->writeInt32(mTracing.writeToFile());
5486 } else {
5487 reply->writeInt32(NO_ERROR);
5488 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005489 }
5490 return NO_ERROR;
5491 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005492 case 1026: { // Get layer tracing status
5493 reply->writeBool(mTracing.isEnabled());
5494 return NO_ERROR;
5495 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005496 // Is a DisplayColorSetting supported?
5497 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005498 const auto display = getDefaultDisplayDevice();
5499 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005500 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005501 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005502
5503 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5504 switch (setting) {
5505 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005506 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005507 break;
5508 case DisplayColorSetting::UNMANAGED:
5509 reply->writeBool(true);
5510 break;
5511 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005512 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005513 break;
5514 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005515 reply->writeBool(
5516 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005517 break;
5518 }
5519 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005520 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005521 // Is VrFlinger active?
5522 case 1028: {
5523 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005524 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005525 return NO_ERROR;
5526 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005527 // Set buffer size for SF tracing (value in KB)
5528 case 1029: {
5529 n = data.readInt32();
5530 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5531 ALOGW("Invalid buffer size: %d KB", n);
5532 reply->writeInt32(BAD_VALUE);
5533 return BAD_VALUE;
5534 }
5535
5536 ALOGD("Updating trace buffer to %d KB", n);
5537 mTracing.setBufferSize(n * 1024);
5538 reply->writeInt32(NO_ERROR);
5539 return NO_ERROR;
5540 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005541 // Is device color managed?
5542 case 1030: {
5543 reply->writeBool(useColorManagement);
5544 return NO_ERROR;
5545 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005546 // Override default composition data space
5547 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5548 // && adb shell stop zygote && adb shell start zygote
5549 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5550 // adb shell stop zygote && adb shell start zygote
5551 case 1031: {
5552 Mutex::Autolock _l(mStateLock);
5553 n = data.readInt32();
5554 if (n) {
5555 n = data.readInt32();
5556 if (n) {
5557 Dataspace dataspace = static_cast<Dataspace>(n);
5558 if (!validateCompositionDataspace(dataspace)) {
5559 return BAD_VALUE;
5560 }
5561 mDefaultCompositionDataspace = dataspace;
5562 }
5563 n = data.readInt32();
5564 if (n) {
5565 Dataspace dataspace = static_cast<Dataspace>(n);
5566 if (!validateCompositionDataspace(dataspace)) {
5567 return BAD_VALUE;
5568 }
5569 mWideColorGamutCompositionDataspace = dataspace;
5570 }
5571 } else {
5572 // restore composition data space.
5573 mDefaultCompositionDataspace = defaultCompositionDataspace;
5574 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5575 }
5576 return NO_ERROR;
5577 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005578 // Set trace flags
5579 case 1033: {
5580 n = data.readUint32();
5581 ALOGD("Updating trace flags to 0x%x", n);
5582 mTracing.setTraceFlags(n);
5583 reply->writeInt32(NO_ERROR);
5584 return NO_ERROR;
5585 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005586 case 1034: {
5587 // TODO(b/129297325): expose this via developer menu option
5588 n = data.readInt32();
5589 if (n && !mRefreshRateOverlay) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07005590 RefreshRateType type;
5591 {
5592 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5593 type = mDesiredActiveConfig.type;
5594 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005595 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07005596 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005597 } else if (!n) {
5598 mRefreshRateOverlay.reset();
5599 }
5600 return NO_ERROR;
5601 }
Ady Abraham34392f72019-04-10 11:29:27 -07005602 case 1035: {
5603 n = data.readInt32();
5604 mDebugDisplayConfigSetByBackdoor = false;
5605 if (n >= 0) {
5606 const auto displayToken = getInternalDisplayToken();
5607 status_t result = setAllowedDisplayConfigs(displayToken, {n});
5608 if (result != NO_ERROR) {
5609 return result;
5610 }
5611 mDebugDisplayConfigSetByBackdoor = true;
5612 }
5613 return NO_ERROR;
5614 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005615 }
5616 }
5617 return err;
5618}
5619
Steven Thomas6d8110b2017-08-31 18:24:21 -07005620void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005621 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005622 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005623}
5624
Ana Krulec7d1d6832018-12-27 11:10:09 -08005625void SurfaceFlinger::repaintEverythingForHWC() {
5626 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005627 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005628}
5629
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005630// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5631class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005632public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005633 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5634 ~WindowDisconnector() {
5635 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005636 }
5637
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005638private:
5639 ANativeWindow* mWindow;
5640 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005641};
5642
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005643status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005644 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5645 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005646 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005647 uint32_t reqWidth, uint32_t reqHeight,
5648 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005649 ISurfaceComposer::Rotation rotation,
5650 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005651 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005652
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005653 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005654
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005655 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5656
Chia-I Wu20261cb2018-08-23 12:55:44 -07005657 sp<DisplayDevice> display;
5658 {
5659 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005660
Chia-I Wu20261cb2018-08-23 12:55:44 -07005661 display = getDisplayDeviceLocked(displayToken);
5662 if (!display) return BAD_VALUE;
5663
Chia-I Wucb023152018-08-28 12:57:23 -07005664 // set the requested width/height to the logical display viewport size
5665 // by default
5666 if (reqWidth == 0 || reqHeight == 0) {
5667 reqWidth = uint32_t(display->getViewport().width());
5668 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005669 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005670 }
5671
Peiyong Lin0e003c92018-09-17 11:09:51 -07005672 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005673 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005674
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005675 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5676 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005677 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005678 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005679}
5680
chaviw93df2ea2019-04-30 16:45:12 -07005681static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5682 switch (colorMode) {
5683 case ColorMode::DISPLAY_P3:
5684 case ColorMode::BT2100_PQ:
5685 case ColorMode::BT2100_HLG:
5686 case ColorMode::DISPLAY_BT2020:
5687 return Dataspace::DISPLAY_P3;
5688 default:
5689 return Dataspace::V0_SRGB;
5690 }
5691}
5692
5693const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5694 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5695 if (displayToken) {
5696 return getDisplayDeviceLocked(displayToken);
5697 }
5698 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5699 // may not have a displayId.
5700 for (const auto& [token, display] : mDisplays) {
5701 if (display->getLayerStack() == displayOrLayerStack) {
5702 return display;
5703 }
5704 }
5705 return nullptr;
5706}
5707
5708status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5709 sp<GraphicBuffer>* outBuffer) {
5710 sp<DisplayDevice> display;
5711 uint32_t width;
5712 uint32_t height;
5713 ui::Transform::orientation_flags captureOrientation;
5714 {
5715 Mutex::Autolock _l(mStateLock);
5716 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5717 if (!display) {
5718 return BAD_VALUE;
5719 }
5720
5721 width = uint32_t(display->getViewport().width());
5722 height = uint32_t(display->getViewport().height());
5723
5724 captureOrientation = fromSurfaceComposerRotation(
5725 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005726 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5727 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5728 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5729 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5730 }
chaviw93df2ea2019-04-30 16:45:12 -07005731 *outDataspace =
5732 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5733 }
5734
5735 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5736 false /* captureSecureLayers */);
5737
5738 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5739 std::placeholders::_1);
5740 bool ignored = false;
5741 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5742 false /* useIdentityTransform */,
5743 ignored /* outCapturedSecureLayers */);
5744}
5745
Robert Carr866455f2019-04-02 16:28:26 -07005746status_t SurfaceFlinger::captureLayers(
5747 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5748 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5749 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5750 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005751 ATRACE_CALL();
5752
5753 class LayerRenderArea : public RenderArea {
5754 public:
Robert Carr578038f2018-03-09 12:25:24 -08005755 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005756 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5757 bool childrenOnly)
5758 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005759 mLayer(layer),
5760 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005761 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005762 mFlinger(flinger),
5763 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005764 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005765 Rect getBounds() const override {
5766 const Layer::State& layerState(mLayer->getDrawingState());
5767 return mLayer->getBufferSize(layerState);
5768 }
Marissa Wall61c58622018-07-18 10:12:20 -07005769 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005770 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005771 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005772 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005773 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005774 }
chaviwa76b2712017-09-20 12:02:26 -07005775 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005776 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005777 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005778 Rect getSourceCrop() const override {
5779 if (mCrop.isEmpty()) {
5780 return getBounds();
5781 } else {
5782 return mCrop;
5783 }
5784 }
Robert Carr578038f2018-03-09 12:25:24 -08005785 class ReparentForDrawing {
5786 public:
5787 const sp<Layer>& oldParent;
5788 const sp<Layer>& newParent;
5789
Vishnu Nair4351ad52019-02-11 14:13:02 -08005790 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5791 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005792 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005793 // Compute and cache the bounds for the new parent layer.
5794 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005795 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005796 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005797 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005798 };
5799
5800 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005801 const Rect sourceCrop = getSourceCrop();
5802 // no need to check rotation because there is none
5803 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5804 sourceCrop.height() != getReqHeight();
5805
Robert Carr578038f2018-03-09 12:25:24 -08005806 if (!mChildrenOnly) {
5807 mTransform = mLayer->getTransform().inverse();
5808 drawLayers();
5809 } else {
5810 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005811 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005812 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
Evan Roskya1f1e152019-01-24 16:17:46 -08005813 bounds.getWidth(), bounds.getHeight(), 0,
5814 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005815
Vishnu Nair4351ad52019-02-11 14:13:02 -08005816 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005817 drawLayers();
5818 }
5819 }
chaviwa76b2712017-09-20 12:02:26 -07005820
chaviwa76b2712017-09-20 12:02:26 -07005821 private:
chaviw7206d492017-11-10 16:16:12 -08005822 const sp<Layer> mLayer;
5823 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005824
5825 // In the "childrenOnly" case we reparent the children to a screenshot
5826 // layer which has no properties set and which does not draw.
5827 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005828 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005829 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005830
5831 SurfaceFlinger* mFlinger;
5832 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005833 };
5834
Robert Carrc0df3122019-04-11 13:18:21 -07005835 int reqWidth = 0;
5836 int reqHeight = 0;
5837 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005838 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005839 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005840
Robert Carrc0df3122019-04-11 13:18:21 -07005841 {
5842 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005843
Robert Carrc0df3122019-04-11 13:18:21 -07005844 parent = fromHandle(layerHandleBinder);
5845 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5846 ALOGE("captureLayers called with an invalid or removed parent");
5847 return NAME_NOT_FOUND;
5848 }
5849
5850 const int uid = IPCThreadState::self()->getCallingUid();
5851 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5852 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5853 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5854 return PERMISSION_DENIED;
5855 }
5856
5857 if (sourceCrop.width() <= 0) {
5858 crop.left = 0;
5859 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5860 }
5861
5862 if (sourceCrop.height() <= 0) {
5863 crop.top = 0;
5864 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5865 }
5866 reqWidth = crop.width() * frameScale;
5867 reqHeight = crop.height() * frameScale;
5868
5869 for (const auto& handle : excludeHandles) {
5870 sp<Layer> excludeLayer = fromHandle(handle);
5871 if (excludeLayer != nullptr) {
5872 excludeLayers.emplace(excludeLayer);
5873 } else {
5874 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5875 return NAME_NOT_FOUND;
5876 }
5877 }
5878 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005879
Chia-I Wu20261cb2018-08-23 12:55:44 -07005880 // really small crop or frameScale
5881 if (reqWidth <= 0) {
5882 reqWidth = 1;
5883 }
5884 if (reqHeight <= 0) {
5885 reqHeight = 1;
5886 }
5887
Robert Carr866455f2019-04-02 16:28:26 -07005888 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5889 auto traverseLayers = [parent, childrenOnly,
5890 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005891 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5892 if (!layer->isVisible()) {
5893 return;
Robert Carr578038f2018-03-09 12:25:24 -08005894 } else if (childrenOnly && layer == parent.get()) {
5895 return;
chaviwa76b2712017-09-20 12:02:26 -07005896 }
Robert Carr866455f2019-04-02 16:28:26 -07005897
5898 sp<Layer> p = layer;
5899 while (p != nullptr) {
5900 if (excludeLayers.count(p) != 0) {
5901 return;
5902 }
5903 p = p->getParent();
5904 }
5905
chaviwa76b2712017-09-20 12:02:26 -07005906 visitor(layer);
5907 });
5908 };
Robert Carr108b2c72019-04-02 16:32:58 -07005909
5910 bool outCapturedSecureLayers = false;
5911 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5912 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005913}
5914
5915status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5916 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005917 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005918 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005919 bool useIdentityTransform,
5920 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005921 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005922
Peiyong Lin0e003c92018-09-17 11:09:51 -07005923 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005924 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5925 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005926 *outBuffer =
5927 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5928 static_cast<android_pixel_format>(reqPixelFormat), 1,
5929 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005930
Robert Carr108b2c72019-04-02 16:32:58 -07005931 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5932 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005933}
5934
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005935status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5936 TraverseLayersFunction traverseLayers,
5937 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005938 bool useIdentityTransform,
5939 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005940 // This mutex protects syncFd and captureResult for communication of the return values from the
5941 // main thread back to this Binder thread
5942 std::mutex captureMutex;
5943 std::condition_variable captureCondition;
5944 std::unique_lock<std::mutex> captureLock(captureMutex);
5945 int syncFd = -1;
5946 std::optional<status_t> captureResult;
5947
Robert Carr03480e22018-01-04 16:02:06 -08005948 const int uid = IPCThreadState::self()->getCallingUid();
5949 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5950
Dominik Laskowski8c001672018-05-30 16:52:06 -07005951 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005952 // If there is a refresh pending, bug out early and tell the binder thread to try again
5953 // after the refresh.
5954 if (mRefreshPending) {
5955 ATRACE_NAME("Skipping screenshot for now");
5956 std::unique_lock<std::mutex> captureLock(captureMutex);
5957 captureResult = std::make_optional<status_t>(EAGAIN);
5958 captureCondition.notify_one();
5959 return;
5960 }
5961
5962 status_t result = NO_ERROR;
5963 int fd = -1;
5964 {
5965 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005966 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005967 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005968 useIdentityTransform, forSystem, &fd,
5969 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005970 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005971 }
5972
5973 {
5974 std::unique_lock<std::mutex> captureLock(captureMutex);
5975 syncFd = fd;
5976 captureResult = std::make_optional<status_t>(result);
5977 captureCondition.notify_one();
5978 }
5979 });
5980
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005981 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005982 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005983 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005984 while (*captureResult == EAGAIN) {
5985 captureResult.reset();
5986 result = postMessageAsync(message);
5987 if (result != NO_ERROR) {
5988 return result;
5989 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005990 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005991 }
5992 result = *captureResult;
5993 }
5994
5995 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005996 sync_wait(syncFd, -1);
5997 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005998 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005999
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006000 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006001}
6002
chaviwa76b2712017-09-20 12:02:26 -07006003void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07006004 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006005 ANativeWindowBuffer* buffer, bool useIdentityTransform,
6006 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07006007 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07006008
chaviwa76b2712017-09-20 12:02:26 -07006009 const auto reqWidth = renderArea.getReqWidth();
6010 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07006011 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07006012 const auto transform = renderArea.getTransform();
6013 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07006014
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006015 renderengine::DisplaySettings clientCompositionDisplay;
6016 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07006017
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006018 // assume that bounds are never offset, and that they are the same as the
6019 // buffer bounds.
6020 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07006021 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07006022 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07006023
6024 // Now take into account the rotation flag. We append a transform that
6025 // rotates the layer stack about the origin, then translate by buffer
6026 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006027 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006028 int displacementX = 0;
6029 int displacementY = 0;
6030 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
6031 switch (rotation) {
6032 case ui::Transform::ROT_90:
6033 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006034 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006035 break;
6036 case ui::Transform::ROT_180:
6037 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006038 displacementY = renderArea.getBounds().getWidth();
6039 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006040 break;
6041 case ui::Transform::ROT_270:
6042 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07006043 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006044 break;
6045 default:
6046 break;
6047 }
Alec Mouriadb75f42019-03-28 21:42:24 -07006048
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006049 // We need to transform the clipping window into the right spot.
6050 // First, rotate the clipping rectangle by the rotation hint to get the
6051 // right orientation
6052 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
6053 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
6054 const vec4 rotClipTL = rotMatrix * clipTL;
6055 const vec4 rotClipBR = rotMatrix * clipBR;
6056 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
6057 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
6058 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
6059 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
6060
6061 // Now reposition the clipping rectangle with the displacement vector
6062 // computed above.
6063 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006064 clientCompositionDisplay.clip =
6065 Rect(newClipLeft + displacementX, newClipTop + displacementY,
6066 newClipRight + displacementX, newClipBottom + displacementY);
6067
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006068 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07006069 clientCompositionDisplay.globalTransform =
6070 clipTransform * clientCompositionDisplay.globalTransform;
6071
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006072 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
6073 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07006074
chaviw50da5042018-04-09 13:49:37 -07006075 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07006076
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006077 renderengine::LayerSettings fillLayer;
6078 fillLayer.source.buffer.buffer = nullptr;
6079 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
6080 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
6081 fillLayer.alpha = half(alpha);
6082 clientCompositionLayers.push_back(fillLayer);
6083
6084 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07006085 traverseLayers([&](Layer* layer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006086 renderengine::LayerSettings layerSettings;
6087 bool prepared = layer->prepareClientLayer(renderArea, useIdentityTransform, clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006088 false, layerSettings);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006089 if (prepared) {
6090 clientCompositionLayers.push_back(layerSettings);
6091 }
chaviwa76b2712017-09-20 12:02:26 -07006092 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006093
6094 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08006095 // Use an empty fence for the buffer fence, since we just created the buffer so
6096 // there is no need for synchronization with the GPU.
6097 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006098 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08006099 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006100 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07006101 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006102
6103 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07006104}
6105
chaviwa76b2712017-09-20 12:02:26 -07006106status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
6107 TraverseLayersFunction traverseLayers,
6108 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07006109 bool useIdentityTransform, bool forSystem,
6110 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08006111 ATRACE_CALL();
6112
chaviwa76b2712017-09-20 12:02:26 -07006113 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07006114 outCapturedSecureLayers =
6115 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07006116 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006117
Robert Carr03480e22018-01-04 16:02:06 -08006118 // We allow the system server to take screenshots of secure layers for
6119 // use in situations like the Screen-rotation animation and place
6120 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07006121 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08006122 ALOGW("FB is protected: PERMISSION_DENIED");
6123 return PERMISSION_DENIED;
6124 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00006125 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07006126 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07006127}
6128
chaviw95ef3c42019-02-14 10:55:09 -08006129void SurfaceFlinger::setInputWindowsFinished() {
6130 Mutex::Autolock _l(mStateLock);
6131
6132 mPendingSyncInputWindows = false;
6133 mTransactionCV.broadcast();
6134}
chaviw5f21a5e2019-02-14 10:00:34 -08006135
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07006136// ---------------------------------------------------------------------------
6137
Dan Stoza412903f2017-04-27 13:42:17 -07006138void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
6139 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006140}
6141
Dan Stoza412903f2017-04-27 13:42:17 -07006142void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
6143 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07006144}
6145
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006146void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07006147 const LayerVector::Visitor& visitor) {
6148 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07006149 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07006150 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006151 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07006152 continue;
6153 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08006154 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07006155 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07006156 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01006157 return;
6158 }
chaviwa76b2712017-09-20 12:02:26 -07006159 if (!layer->isVisible()) {
6160 return;
6161 }
6162 visitor(layer);
6163 });
6164 }
6165}
6166
Daniel Solomond916d942019-08-19 19:31:09 -07006167void SurfaceFlinger::setPreferredDisplayConfig() {
6168 const auto& type = mScheduler->getPreferredRefreshRateType();
6169 const auto& config = mRefreshRateConfigs.getRefreshRate(type);
6170 if (config && isDisplayConfigAllowed(config->configId)) {
6171 ALOGV("switching to Scheduler preferred config %d", config->configId);
6172 setDesiredActiveConfig({type, config->configId, Scheduler::ConfigEvent::Changed});
6173 } else {
6174 // Set the highest allowed config by iterating backwards on available refresh rates
6175 const auto& refreshRates = mRefreshRateConfigs.getRefreshRates();
6176 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
6177 if (iter->second && isDisplayConfigAllowed(iter->second->configId)) {
6178 ALOGV("switching to allowed config %d", iter->second->configId);
6179 setDesiredActiveConfig({iter->first, iter->second->configId,
6180 Scheduler::ConfigEvent::Changed});
6181 }
6182 }
6183 }
6184}
6185
Dominik Laskowski22488f62019-03-28 09:53:04 -07006186void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
6187 const std::vector<int32_t>& allowedConfigs) {
6188 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08006189 return;
6190 }
6191
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006192 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
6193 allowedConfigs.end());
6194 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
6195 return;
6196 }
6197
Ady Abraham838de062019-02-04 10:24:03 -08006198 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07006199 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
6200
6201 // TODO(b/140204874): This hack triggers a notification that something has changed, so
6202 // that listeners that care about a change in allowed configs can get the notification.
6203 // Giving current ActiveConfig so that most other listeners would just drop the event
6204 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
6205 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08006206
Daniel Solomond916d942019-08-19 19:31:09 -07006207 setPreferredDisplayConfig();
Ady Abraham838de062019-02-04 10:24:03 -08006208}
6209
Dominik Laskowski22488f62019-03-28 09:53:04 -07006210status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08006211 const std::vector<int32_t>& allowedConfigs) {
6212 ATRACE_CALL();
6213
Dominik Laskowski22488f62019-03-28 09:53:04 -07006214 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08006215 return BAD_VALUE;
6216 }
6217
Ady Abraham34392f72019-04-10 11:29:27 -07006218 if (mDebugDisplayConfigSetByBackdoor) {
6219 // ignore this request as config is overridden by backdoor
6220 return NO_ERROR;
6221 }
6222
Ady Abraham838de062019-02-04 10:24:03 -08006223 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07006224 const auto display = getDisplayDeviceLocked(displayToken);
6225 if (!display) {
6226 ALOGE("Attempt to set allowed display configs for invalid display token %p",
6227 displayToken.get());
6228 } else if (display->isVirtual()) {
6229 ALOGW("Attempt to set allowed display configs for virtual display");
6230 } else {
6231 setAllowedDisplayConfigsInternal(display, allowedConfigs);
6232 }
Ady Abraham838de062019-02-04 10:24:03 -08006233 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07006234
Ady Abraham838de062019-02-04 10:24:03 -08006235 return NO_ERROR;
6236}
6237
Dominik Laskowski22488f62019-03-28 09:53:04 -07006238status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006239 std::vector<int32_t>* outAllowedConfigs) {
6240 ATRACE_CALL();
6241
Dominik Laskowski22488f62019-03-28 09:53:04 -07006242 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006243 return BAD_VALUE;
6244 }
6245
Dominik Laskowski22488f62019-03-28 09:53:04 -07006246 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006247
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006248 const auto display = getDisplayDeviceLocked(displayToken);
6249 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006250 return NAME_NOT_FOUND;
6251 }
6252
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006253 if (display->isPrimary()) {
6254 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
6255 }
6256
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006257 return NO_ERROR;
6258}
6259
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006260void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006261 mFlinger->setInputWindowsFinished();
6262}
6263
Robert Carrc0df3122019-04-11 13:18:21 -07006264sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6265 BBinder *b = handle->localBinder();
6266 if (b == nullptr) {
6267 return nullptr;
6268 }
6269 auto it = mLayersByLocalBinderToken.find(b);
6270 if (it != mLayersByLocalBinderToken.end()) {
6271 return it->second.promote();
6272 }
6273 return nullptr;
6274}
6275
Alec Mouri4545a8a2019-08-08 20:05:32 -07006276void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6277 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6278}
6279
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006280} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006281
Mathias Agopian3f844832013-08-07 21:24:32 -07006282#if defined(__gl_h_)
6283#error "don't include gl/gl.h in this file"
6284#endif
6285
6286#if defined(__gl2_h_)
6287#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006288#endif