blob: 15550799bfbf0c21a857ccdf836bb15150b8e4b3 [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 Piqueab039b52019-02-13 14:22:42 -080041#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070043#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080044#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070049#include <gui/DebugEGLImageTracker.h>
50
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070098#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070099#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700101#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/EventControlThread.h"
103#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -0700104#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700105#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700106#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700107#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800108#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700109
Mathias Agopianff2ed702013-09-01 21:36:12 -0700110#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700111
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700112#include "android-base/parseint.h"
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
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700165ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
166 switch (rotation) {
167 case ISurfaceComposer::eRotateNone:
168 return ui::Transform::ROT_0;
169 case ISurfaceComposer::eRotate90:
170 return ui::Transform::ROT_90;
171 case ISurfaceComposer::eRotate180:
172 return ui::Transform::ROT_180;
173 case ISurfaceComposer::eRotate270:
174 return ui::Transform::ROT_270;
175 }
176 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
177 return ui::Transform::ROT_0;
178}
179
Peiyong Linfca547f2018-07-09 13:03:33 -0700180#pragma clang diagnostic pop
181
Steven Thomasb02664d2017-07-26 18:48:28 -0700182class ConditionalLock {
183public:
184 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
185 if (lock) {
186 mMutex.lock();
187 }
188 }
189 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
190private:
191 Mutex& mMutex;
192 bool mLocked;
193};
Peiyong Linfca547f2018-07-09 13:03:33 -0700194
Peiyong Lin9d846a52018-11-05 13:18:20 -0800195// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
196bool validateCompositionDataspace(Dataspace dataspace) {
197 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
198}
199
Steven Thomasb02664d2017-07-26 18:48:28 -0700200} // namespace anonymous
201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202// ---------------------------------------------------------------------------
203
Mathias Agopian99b49842011-06-27 16:05:52 -0700204const String16 sHardwareTest("android.permission.HARDWARE_TEST");
205const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
206const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
207const String16 sDump("android.permission.DUMP");
208
209// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700210int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700211bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800212uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800213bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800214bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800215int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600216bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700217int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700218bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700219bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700220Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
221ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
222Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
223ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700224
Kalle Raitaa099a242017-01-11 11:17:29 -0800225std::string getHwcServiceName() {
226 char value[PROPERTY_VALUE_MAX] = {};
227 property_get("debug.sf.hwc_service_name", value, "default");
228 ALOGI("Using HWComposer service: '%s'", value);
229 return std::string(value);
230}
231
232bool useTrebleTestingOverride() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.treble_testing_override", value, "false");
235 ALOGI("Treble testing override: '%s'", value);
236 return std::string(value) == "true";
237}
238
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800239std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
240 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800241 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700242 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800243 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700244 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800245 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700246 return std::string("Enhanced");
247 default:
248 return std::string("Unknown ") +
249 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251}
252
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700253SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800254
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700255SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
256 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700257 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700258 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700259 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700261 mCompositionEngine(mFactory.createCompositionEngine()),
262 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900267 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 mDefaultCompositionDataspace =
285 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700286 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
287 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 defaultCompositionDataspace = mDefaultCompositionDataspace;
289 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
290 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
291 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
292 wideColorGamutCompositionPixelFormat =
293 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700294
Yichi Chenda901bf2019-06-28 14:58:27 +0800295 mColorSpaceAgnosticDataspace =
296 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
301 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
302 switch (tmpPrimaryDisplayOrientation) {
303 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700304 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800305 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700307 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800308 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700310 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800311 break;
312 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700313 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
315 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700316 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800317
Sundong Ahn85131bd2019-02-18 15:51:53 +0900318 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 // debugging stuff...
321 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700322
Mathias Agopianb4b17302013-03-20 18:36:41 -0700323 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700324 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 property_get("debug.sf.showupdates", value, "0");
327 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700328
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700329 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000330
331 // DDMS debugging deprecated (b/120782499)
332 property_get("debug.sf.ddms", value, "0");
333 int debugDdms = atoi(value);
334 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700335
336 property_get("debug.sf.disable_backpressure", value, "0");
337 mPropagateBackpressure = !atoi(value);
338 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700339
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800340 property_get("debug.sf.enable_hwc_vds", value, "0");
341 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800342 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800343
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800344 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800345 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800346 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700347
Yiwei Zhang243b3782018-05-15 17:40:04 -0700348 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700349 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
350 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
351
Ana Krulece5a06e02019-03-06 17:09:03 -0800352 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800353 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800354
355 int int_value = atoi(value);
356 if (int_value) {
357 mUseSmart90ForVideo = true;
358 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800359
Dan Stozaec460082018-12-17 15:35:09 -0800360 property_get("debug.sf.luma_sampling", value, "1");
361 mLumaSampling = atoi(value);
362
Romain Guy11d63f42017-07-20 12:47:14 -0700363 // We should be reading 'persist.sys.sf.color_saturation' here
364 // but since /data may be encrypted, we need to wait until after vold
365 // comes online to attempt to read the property. The property is
366 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800367
368 if (useTrebleTestingOverride()) {
369 // Without the override SurfaceFlinger cannot connect to HIDL
370 // services that are not listed in the manifests. Considered
371 // deriving the setting from the set service name, but it
372 // would be brittle if the name that's not 'default' is used
373 // for production purposes later on.
374 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
375 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800376}
377
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800378void SurfaceFlinger::onFirstRef()
379{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800380 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800381}
382
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700383SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800384
Dan Stozac7014012014-02-14 15:03:43 -0800385void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386{
387 // the window manager died on us. prepare its eulogy.
388
Andy McFadden13a082e2012-08-24 10:16:42 -0700389 // restore initial conditions (default device unblank, etc)
390 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800391
392 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700393 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800394}
395
Robert Carr1db73f62016-12-21 12:58:51 -0800396static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700397 status_t err = client->initCheck();
398 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800399 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400 }
Robert Carr1db73f62016-12-21 12:58:51 -0800401 return nullptr;
402}
403
404sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
405 return initClient(new Client(this));
406}
407
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700408sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
409 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700410{
411 class DisplayToken : public BBinder {
412 sp<SurfaceFlinger> flinger;
413 virtual ~DisplayToken() {
414 // no more references, this display must be terminated
415 Mutex::Autolock _l(flinger->mStateLock);
416 flinger->mCurrentState.displays.removeItem(this);
417 flinger->setTransactionFlags(eDisplayTransactionNeeded);
418 }
419 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700420 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700421 : flinger(flinger) {
422 }
423 };
424
425 sp<BBinder> token = new DisplayToken(this);
426
427 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700428 // Display ID is assigned when virtual display is allocated by HWC.
429 DisplayDeviceState state;
430 state.isSecure = secure;
431 state.displayName = displayName;
432 mCurrentState.displays.add(token, state);
433 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700434 return token;
435}
436
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700437void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700438 Mutex::Autolock _l(mStateLock);
439
Dominik Laskowski075d3172018-05-24 15:50:06 -0700440 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
441 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700442 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700443 return;
444 }
445
Dominik Laskowski075d3172018-05-24 15:50:06 -0700446 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
447 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700448 ALOGE("destroyDisplay called for non-virtual display");
449 return;
450 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 mInterceptor->saveDisplayDeletion(state.sequenceId);
452 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700453 setTransactionFlags(eDisplayTransactionNeeded);
454}
455
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800456std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
457 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800459 const auto internalDisplayId = getInternalDisplayIdLocked();
460 if (!internalDisplayId) {
461 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462 }
463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800464 std::vector<PhysicalDisplayId> displayIds;
465 displayIds.reserve(mPhysicalDisplayTokens.size());
466 displayIds.push_back(internalDisplayId->value);
467
468 for (const auto& [id, token] : mPhysicalDisplayTokens) {
469 if (id != *internalDisplayId) {
470 displayIds.push_back(id.value);
471 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700472 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800474 return displayIds;
475}
476
477sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
478 Mutex::Autolock lock(mStateLock);
479 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700480}
481
Ady Abraham37965d42018-11-01 13:43:32 -0700482status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
483 if (!outGetColorManagement) {
484 return BAD_VALUE;
485 }
486 *outGetColorManagement = useColorManagement;
487 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700488}
489
Lloyd Pique441d5042018-10-18 16:49:51 -0700490HWComposer& SurfaceFlinger::getHwComposer() const {
491 return mCompositionEngine->getHwComposer();
492}
493
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700494renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
495 return mCompositionEngine->getRenderEngine();
496}
497
Lloyd Pique70d91362018-10-18 16:02:55 -0700498compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
499 return *mCompositionEngine.get();
500}
501
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800502void SurfaceFlinger::bootFinished()
503{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700504 if (mStartPropertySetThread->join() != NO_ERROR) {
505 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800506 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507 const nsecs_t now = systemTime();
508 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000509 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700510
Mikael Pessa90092f42019-08-26 17:22:04 -0700511 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700512
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700513 // wait patiently for the window manager death
514 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700515 mWindowManager = defaultServiceManager()->getService(name);
516 if (mWindowManager != 0) {
517 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700518 }
Robert Carr720e5062018-07-30 17:45:14 -0700519 sp<IBinder> input(defaultServiceManager()->getService(
520 String16("inputflinger")));
521 if (input == nullptr) {
522 ALOGE("Failed to link to input service");
523 } else {
524 mInputFlinger = interface_cast<IInputFlinger>(input);
525 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700526
Steven Thomas050b2c82017-03-06 11:45:16 -0800527 if (mVrFlinger) {
528 mVrFlinger->OnBootFinished();
529 }
530
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700532 // formerly we would just kill the process, but we now ask it to exit so it
533 // can choose where to stop the animation.
534 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700535
536 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
537 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
538 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700539
Ana Krulecbd6654b2019-02-15 15:18:15 -0800540 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800541 readPersistentProperties();
542 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800543
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700544 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
545 // set the refresh rate according to the policy
546 const auto& performanceRefreshRate =
547 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800548
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700549 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
550 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
551 } else {
552 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
553 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800554 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800555 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800556}
557
Dan Stoza436ccf32018-06-21 12:10:12 -0700558uint32_t SurfaceFlinger::getNewTexture() {
559 {
560 std::lock_guard lock(mTexturePoolMutex);
561 if (!mTexturePool.empty()) {
562 uint32_t name = mTexturePool.back();
563 mTexturePool.pop_back();
564 ATRACE_INT("TexturePoolSize", mTexturePool.size());
565 return name;
566 }
567
568 // The pool was too small, so increase it for the future
569 ++mTexturePoolSize;
570 }
571
572 // The pool was empty, so we need to get a new texture name directly using a
573 // blocking call to the main thread
574 uint32_t name = 0;
575 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
576 return name;
577}
578
Mathias Agopian3f844832013-08-07 21:24:32 -0700579void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700580 std::lock_guard lock(mTexturePoolMutex);
581 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
582 // to actually delete this or not based on mTexturePoolSize
583 mTexturePool.push_back(texture);
584 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700585}
586
Wei Wangf9b05ee2017-07-19 20:59:39 -0700587// Do not call property_set on main thread which will be blocked by init
588// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700590 ALOGI( "SurfaceFlinger's main thread ready to run. "
591 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700592 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900593
Steven Thomasb02664d2017-07-26 18:48:28 -0700594 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800595
Steven Thomasb02664d2017-07-26 18:48:28 -0700596 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700597 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700598 renderEngineFeature |= (useColorManagement ?
599 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700600 renderEngineFeature |= (useContextPriority ?
601 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700602 renderEngineFeature |=
603 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
604 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700605
606 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800607 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700608 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700609 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800610 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700611
612 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
613 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700614 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
615 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800616 // Process any initial hotplug and resulting display changes.
617 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700618 const auto display = getDefaultDisplayDeviceLocked();
619 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700620 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700621 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800622
Steven Thomas050b2c82017-03-06 11:45:16 -0800623 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700624 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700625 // This callback is called from the vr flinger dispatch thread. We
626 // need to call signalTransaction(), which requires holding
627 // mStateLock when we're not on the main thread. Acquiring
628 // mStateLock from the vr flinger dispatch thread might trigger a
629 // deadlock in surface flinger (see b/66916578), so post a message
630 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700631 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700632 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
633 mVrFlingerRequestsDisplay = requestDisplay;
634 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800636 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700637 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
638 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700639 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700640 .value_or(0),
641 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800642 if (!mVrFlinger) {
643 ALOGE("Failed to start vrflinger");
644 }
645 }
646
Mathias Agopian92a979a2012-08-02 18:32:23 -0700647 // initialize our drawing state
648 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700649
Andy McFadden13a082e2012-08-24 10:16:42 -0700650 // set initial conditions (e.g. unblank default device)
651 initializeDisplays();
652
Steven Thomas137d4bc2019-07-25 16:55:14 -0700653 char primeShaderCache[PROPERTY_VALUE_MAX];
654 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
655 if (atoi(primeShaderCache)) {
656 getRenderEngine().primeCache();
657 }
Dan Stoza4e637772016-07-28 13:31:51 -0700658
Wei Wangf9b05ee2017-07-19 20:59:39 -0700659 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700660
661 const bool presentFenceReliable =
662 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
663 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664
665 if (mStartPropertySetThread->Start() != NO_ERROR) {
666 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800667 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800668
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700670}
671
Romain Guy11d63f42017-07-20 12:47:14 -0700672void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700673 Mutex::Autolock _l(mStateLock);
674
Romain Guy11d63f42017-07-20 12:47:14 -0700675 char value[PROPERTY_VALUE_MAX];
676
677 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800678 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700679 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800680 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100681
682 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700683 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800684
685 property_get("persist.sys.sf.color_mode", value, "0");
686 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700687}
688
Mathias Agopiana67e4182012-06-19 17:26:12 -0700689void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800690 // Start boot animation service by setting a property mailbox
691 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800693 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694 if (mStartPropertySetThread->join() != NO_ERROR) {
695 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800696 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700697}
698
Mathias Agopian875d8e12013-06-07 15:35:48 -0700699size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700700 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700701}
702
Mathias Agopian875d8e12013-06-07 15:35:48 -0700703size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700704 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700705}
706
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800707// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800708
Jamie Gennis582270d2011-08-17 18:19:00 -0700709bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800710 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800711 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800712 return authenticateSurfaceTextureLocked(bufferProducer);
713}
714
715bool SurfaceFlinger::authenticateSurfaceTextureLocked(
716 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800717 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800718 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800719}
720
Brian Anderson6b376712017-04-04 10:51:39 -0700721status_t SurfaceFlinger::getSupportedFrameTimestamps(
722 std::vector<FrameEvent>* outSupported) const {
723 *outSupported = {
724 FrameEvent::REQUESTED_PRESENT,
725 FrameEvent::ACQUIRE,
726 FrameEvent::LATCH,
727 FrameEvent::FIRST_REFRESH_START,
728 FrameEvent::LAST_REFRESH_START,
729 FrameEvent::GPU_COMPOSITION_DONE,
730 FrameEvent::DEQUEUE_READY,
731 FrameEvent::RELEASE,
732 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700733 ConditionalLock _l(mStateLock,
734 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700735 if (!getHwComposer().hasCapability(
736 HWC2::Capability::PresentFenceIsNotReliable)) {
737 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
738 }
739 return NO_ERROR;
740}
741
Dominik Laskowski22488f62019-03-28 09:53:04 -0700742status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
743 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700744 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700745 return BAD_VALUE;
746 }
747
Dominik Laskowski22488f62019-03-28 09:53:04 -0700748 Mutex::Autolock lock(mStateLock);
749
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800750 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700751 if (!displayId) {
752 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700753 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755 // TODO: Not sure if display density should handled by SF any longer
756 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700757 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700759 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800760 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700761 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 }
763 return density;
764 }
765 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700766 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700767 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700768 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700769 return getDensityFromProperty("ro.sf.lcd_density"); }
770 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700771
Dan Stoza7f7da322014-05-02 15:26:25 -0700772 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700773
Dominik Laskowski075d3172018-05-24 15:50:06 -0700774 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700775 DisplayInfo info = DisplayInfo();
776
Dan Stoza9e56aa02015-11-02 13:00:03 -0800777 float xdpi = hwConfig->getDpiX();
778 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700779
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700780 info.w = hwConfig->getWidth();
781 info.h = hwConfig->getHeight();
782 // Default display viewport to display width and height
783 info.viewportW = info.w;
784 info.viewportH = info.h;
785
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800786 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700787 // The density of the device is provided by a build property
788 float density = Density::getBuildDensity() / 160.0f;
789 if (density == 0) {
790 // the build doesn't provide a density -- this is wrong!
791 // use xdpi instead
792 ALOGE("ro.sf.lcd_density must be defined as a build property");
793 density = xdpi / 160.0f;
794 }
795 if (Density::getEmuDensity()) {
796 // if "qemu.sf.lcd_density" is specified, it overrides everything
797 xdpi = ydpi = density = Density::getEmuDensity();
798 density /= 160.0f;
799 }
800 info.density = density;
801
802 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700803 const auto display = getDefaultDisplayDeviceLocked();
804 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700805
806 // This is for screenrecord
807 const Rect viewport = display->getViewport();
808 if (viewport.isValid()) {
809 info.viewportW = uint32_t(viewport.getWidth());
810 info.viewportH = uint32_t(viewport.getHeight());
811 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 } else {
813 // TODO: where should this value come from?
814 static const int TV_DENSITY = 213;
815 info.density = TV_DENSITY / 160.0f;
816 info.orientation = 0;
817 }
818
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 info.xdpi = xdpi;
820 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700822 const auto refreshRateType =
823 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700824 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
825 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800826
Andy McFadden91b2ca82014-06-13 14:04:23 -0700827 // This is how far in advance a buffer must be queued for
828 // presentation at a given time. If you want a buffer to appear
829 // on the screen at time N, you must submit the buffer before
830 // (N - presentationDeadline).
831 //
832 // Normally it's one full refresh period (to give SF a chance to
833 // latch the buffer), but this can be reduced by configuring a
834 // DispSync offset. Any additional delays introduced by the hardware
835 // composer or panel must be accounted for here.
836 //
837 // We add an additional 1ms to allow for processing time and
838 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700839 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
841 // All non-virtual displays are currently considered secure.
842 info.secure = true;
843
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800844 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700845 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800846 std::swap(info.w, info.h);
847 }
848
Michael Wright28f24d02016-07-12 13:30:53 -0700849 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700850 }
851
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 return NO_ERROR;
853}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700854
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
856 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700857 return BAD_VALUE;
858 }
859
Ana Krulecc2870422019-01-29 19:00:58 -0800860 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700861 return NO_ERROR;
862}
863
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700864int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
865 const auto display = getDisplayDevice(displayToken);
866 if (!display) {
867 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800868 return BAD_VALUE;
869 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700870
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700871 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700872}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700873
Ady Abraham03b02dd2019-03-21 15:40:11 -0700874void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800875 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800876
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800877 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800878 // config twice. However event generation config might have changed so we need to update it
879 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800880 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700881 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
882 mDesiredActiveConfig = info;
883 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800884
885 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800886 // This will trigger HWC refresh without resetting the idle timer.
887 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700888 // Start receiving vsync samples now, so that we can detect a period
889 // switch.
890 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700891 // As we called to set period, we will call to onRefreshRateChangeCompleted once
892 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700893 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700894 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700895 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800896 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800897 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700898
899 if (mRefreshRateOverlay) {
900 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
901 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800902}
903
904status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
905 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800906
907 std::vector<int32_t> allowedConfig;
908 allowedConfig.push_back(mode);
909
910 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800911}
912
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800913void SurfaceFlinger::setActiveConfigInternal() {
914 ATRACE_CALL();
915
Dominik Laskowski22488f62019-03-28 09:53:04 -0700916 const auto display = getDefaultDisplayDeviceLocked();
917 if (!display) {
918 return;
919 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800920
Dominik Laskowski22488f62019-03-28 09:53:04 -0700921 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700922 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
923 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700924
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800925 display->setActiveConfig(mUpcomingActiveConfig.configId);
926
Alec Mouri754c98a2019-03-18 18:53:42 -0700927 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700928 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700930
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800931 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800932 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
933 mUpcomingActiveConfig.configId);
934 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800935}
936
Ady Abraham53852a52019-05-28 18:07:44 -0700937void SurfaceFlinger::desiredActiveConfigChangeDone() {
938 std::lock_guard<std::mutex> lock(mActiveConfigLock);
939 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
940 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700941
942 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
943 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700944 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700945}
946
Dominik Laskowski22488f62019-03-28 09:53:04 -0700947bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800948 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800949 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700950 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800951 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700952 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800953 return true;
954 }
955
956 // We received the present fence from the HWC, so we assume it successfully updated
957 // the config, hence we update SF.
958 mCheckPendingFence = false;
959 setActiveConfigInternal();
960 }
961
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962 // Store the local variable to release the lock.
963 ActiveConfigInfo desiredActiveConfig;
964 {
965 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800966 if (!mDesiredActiveConfigChanged) {
967 return false;
968 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800969 desiredActiveConfig = mDesiredActiveConfig;
970 }
971
Dominik Laskowski22488f62019-03-28 09:53:04 -0700972 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
974 // display is not valid or we are already in the requested mode
975 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700976 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800977 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800979
Ady Abraham838de062019-02-04 10:24:03 -0800980 // Desired active config was set, it is different than the config currently in use, however
981 // allowed configs might have change by the time we process the refresh.
982 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -0700983 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -0700984 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -0800985 return false;
986 }
Alec Mouri7f015182019-07-11 13:56:22 -0700987
Ady Abrahamb838aed2019-02-12 15:30:16 -0800988 mUpcomingActiveConfig = desiredActiveConfig;
989 const auto displayId = display->getId();
990 LOG_ALWAYS_FATAL_IF(!displayId);
991
992 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
993 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
994
995 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -0800996 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -0700997 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800998 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700999}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1002 Vector<ColorMode>* outColorModes) {
1003 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001004 return BAD_VALUE;
1005 }
1006
Peiyong Lina52f0292018-03-14 17:26:31 -07001007 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001008 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001009 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001010 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1011
1012 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1013 if (!displayId) {
1014 return NAME_NOT_FOUND;
1015 }
1016
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001018 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001019 }
Michael Wright28f24d02016-07-12 13:30:53 -07001020 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001021
1022 // If it's built-in display and the configuration claims it's not wide color capable,
1023 // filter out all wide color modes. The typical reason why this happens is that the
1024 // hardware is not good enough to support GPU composition of wide color, and thus the
1025 // OEMs choose to disable this capability.
1026 if (isInternalDisplay && !hasWideColorDisplay) {
1027 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1028 isWideColorMode);
1029 } else {
1030 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1031 }
Michael Wright28f24d02016-07-12 13:30:53 -07001032
1033 return NO_ERROR;
1034}
1035
Daniel Solomon42d04562019-01-20 21:03:19 -08001036status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1037 ui::DisplayPrimaries &primaries) {
1038 if (!displayToken) {
1039 return BAD_VALUE;
1040 }
1041
1042 // Currently we only support this API for a single internal display.
1043 if (getInternalDisplayToken() != displayToken) {
1044 return BAD_VALUE;
1045 }
1046
1047 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1048 return NO_ERROR;
1049}
1050
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001051ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1052 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001053 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001054 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001056}
1057
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001059 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001060 Vector<ColorMode> modes;
1061 getDisplayColorModes(displayToken, &modes);
1062 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1063 if (mode < ColorMode::NATIVE || !exists) {
1064 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1065 decodeColorMode(mode).c_str(), mode, displayToken.get());
1066 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001067 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068 const auto display = getDisplayDevice(displayToken);
1069 if (!display) {
1070 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1071 decodeColorMode(mode).c_str(), mode, displayToken.get());
1072 } else if (display->isVirtual()) {
1073 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1074 decodeColorMode(mode).c_str(), mode);
1075 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001076 display->getCompositionDisplay()->setColorProfile(
1077 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1078 RenderIntent::COLORIMETRIC,
1079 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 }
1081 }));
1082
Michael Wright28f24d02016-07-12 13:30:53 -07001083 return NO_ERROR;
1084}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001085
Svetoslavd85084b2014-03-20 10:28:31 -07001086status_t SurfaceFlinger::clearAnimationFrameStats() {
1087 Mutex::Autolock _l(mStateLock);
1088 mAnimFrameTracker.clearStats();
1089 return NO_ERROR;
1090}
1091
1092status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1093 Mutex::Autolock _l(mStateLock);
1094 mAnimFrameTracker.getStats(outStats);
1095 return NO_ERROR;
1096}
1097
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1099 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001100 Mutex::Autolock _l(mStateLock);
1101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const auto display = getDisplayDeviceLocked(displayToken);
1103 if (!display) {
1104 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001105 return BAD_VALUE;
1106 }
1107
Peiyong Linfb069302018-04-25 14:34:31 -07001108 // At this point the DisplayDeivce should already be set up,
1109 // meaning the luminance information is already queried from
1110 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001112 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1113 capabilities.getDesiredMaxLuminance(),
1114 capabilities.getDesiredMaxAverageLuminance(),
1115 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001116
1117 return NO_ERROR;
1118}
1119
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001120status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1121 ui::PixelFormat* outFormat,
1122 ui::Dataspace* outDataspace,
1123 uint8_t* outComponentMask) const {
1124 if (!outFormat || !outDataspace || !outComponentMask) {
1125 return BAD_VALUE;
1126 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001127 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001128 if (!display || !display->getId()) {
1129 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1130 return BAD_VALUE;
1131 }
1132 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1133 outDataspace, outComponentMask);
1134}
1135
Kevin DuBois74e53772018-11-19 10:52:38 -08001136status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1137 bool enable, uint8_t componentMask,
1138 uint64_t maxFrames) const {
1139 const auto display = getDisplayDevice(displayToken);
1140 if (!display || !display->getId()) {
1141 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1142 return BAD_VALUE;
1143 }
1144
1145 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1146 componentMask, maxFrames);
1147}
1148
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001149status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1150 uint64_t maxFrames, uint64_t timestamp,
1151 DisplayedFrameStats* outStats) const {
1152 const auto display = getDisplayDevice(displayToken);
1153 if (!display || !display->getId()) {
1154 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1155 return BAD_VALUE;
1156 }
1157
1158 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1159 outStats);
1160}
1161
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001162status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1163 if (!outSupported) {
1164 return BAD_VALUE;
1165 }
1166 *outSupported = getRenderEngine().supportsProtectedContent();
1167 return NO_ERROR;
1168}
1169
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001170status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1171 bool* outIsWideColorDisplay) const {
1172 if (!displayToken || !outIsWideColorDisplay) {
1173 return BAD_VALUE;
1174 }
1175 Mutex::Autolock _l(mStateLock);
1176 const auto display = getDisplayDeviceLocked(displayToken);
1177 if (!display) {
1178 return BAD_VALUE;
1179 }
Peiyong Linff84a152019-05-17 18:36:19 -07001180
1181 // Use hasWideColorDisplay to override built-in display.
1182 const auto displayId = display->getId();
1183 if (displayId && displayId == getInternalDisplayIdLocked()) {
1184 *outIsWideColorDisplay = hasWideColorDisplay;
1185 return NO_ERROR;
1186 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001187 *outIsWideColorDisplay = display->hasWideColorGamut();
1188 return NO_ERROR;
1189}
1190
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001191status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001192 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001193 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001194
Chia-I Wu90f669f2017-10-05 14:24:41 -07001195 if (mInjectVSyncs == enable) {
1196 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001197 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001198
Ady Abraham46e2f3e2019-03-18 16:40:15 -07001199 // TODO(b/128863962): Part of the Injector should be refactored, so that it
Ana Krulec98b5b242018-08-10 15:03:23 -07001200 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001201 if (enable) {
1202 ALOGV("VSync Injections enabled");
1203 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001204 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001205 mInjectorEventThread = std::make_unique<
Dominik Laskowskif654d572018-12-20 11:03:06 -08001206 impl::EventThread>(mVSyncInjector.get(),
Lloyd Pique24b0a482018-03-09 18:52:26 -08001207 impl::EventThread::InterceptVSyncsCallback(),
1208 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001209 }
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001210 mEventQueue->setEventThread(mInjectorEventThread.get(), [&] { mScheduler->resync(); });
Chia-I Wu90f669f2017-10-05 14:24:41 -07001211 } else {
1212 ALOGV("VSync Injections disabled");
Ana Krulecc2870422019-01-29 19:00:58 -08001213 mEventQueue->setEventThread(mScheduler->getEventThread(mSfConnectionHandle),
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001214 [&] { mScheduler->resync(); });
Chia-I Wu90f669f2017-10-05 14:24:41 -07001215 }
1216
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001217 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001218 }));
1219
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001220 return NO_ERROR;
1221}
1222
1223status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001224 Mutex::Autolock _l(mStateLock);
1225
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001226 if (!mInjectVSyncs) {
1227 ALOGE("VSync Injections not enabled");
1228 return BAD_VALUE;
1229 }
1230 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1231 ALOGV("Injecting VSync inside SurfaceFlinger");
1232 mVSyncInjector->onInjectSyncEvent(when);
1233 }
1234 return NO_ERROR;
1235}
1236
Lloyd Pique755e3192018-01-31 16:46:15 -08001237status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1238 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001239 // Try to acquire a lock for 1s, fail gracefully
1240 const status_t err = mStateLock.timedLock(s2ns(1));
1241 const bool locked = (err == NO_ERROR);
1242 if (!locked) {
1243 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1244 return TIMED_OUT;
1245 }
1246
1247 outLayers->clear();
1248 mCurrentState.traverseInZOrder([&](Layer* layer) {
1249 outLayers->push_back(layer->getLayerDebugInfo());
1250 });
1251
1252 mStateLock.unlock();
1253 return NO_ERROR;
1254}
1255
Peiyong Linc6780972018-10-28 15:24:08 -07001256status_t SurfaceFlinger::getCompositionPreference(
1257 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1258 Dataspace* outWideColorGamutDataspace,
1259 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001260 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001261 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001262 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001263 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001264 return NO_ERROR;
1265}
1266
Dan Stozaec460082018-12-17 15:35:09 -08001267status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1268 const sp<IBinder>& stopLayerHandle,
1269 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001270 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001271 return BAD_VALUE;
1272 }
1273 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001274 return NO_ERROR;
1275}
1276
Dan Stozaec460082018-12-17 15:35:09 -08001277status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001278 if (!listener) {
1279 return BAD_VALUE;
1280 }
Dan Stozaec460082018-12-17 15:35:09 -08001281 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001282 return NO_ERROR;
1283}
Dan Gittik57e63c52019-01-18 16:37:54 +00001284
1285status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1286 bool* outSupport) const {
1287 if (!displayToken || !outSupport) {
1288 return BAD_VALUE;
1289 }
1290 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1291 if (!displayId) {
1292 return NAME_NOT_FOUND;
1293 }
1294 *outSupport =
1295 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1296 return NO_ERROR;
1297}
1298
1299status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1300 float brightness) const {
1301 if (!displayToken) {
1302 return BAD_VALUE;
1303 }
1304 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1305 if (!displayId) {
1306 return NAME_NOT_FOUND;
1307 }
1308 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1309}
1310
Ady Abraham8532d012019-05-08 14:50:56 -07001311status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1312 PowerHint powerHint = static_cast<PowerHint>(hintId);
1313
1314 if (powerHint == PowerHint::INTERACTION) {
1315 mScheduler->notifyTouchEvent();
1316 }
1317
1318 return NO_ERROR;
1319}
1320
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001321// ----------------------------------------------------------------------------
1322
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001323sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001324 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001325 const auto& handle =
1326 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001327
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001328 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001329}
1330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001331// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001332
1333void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001334 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001335}
1336
1337void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001338 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001339 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001340}
1341
1342void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001343 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001344 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345}
1346
1347void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001348 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001349 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001350}
1351
1352status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001353 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001354 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001355}
1356
1357status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001358 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001359 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001360 if (res == NO_ERROR) {
1361 msg->wait();
1362 }
1363 return res;
1364}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001365
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001366void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001367 do {
1368 waitForEvent();
1369 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001370}
1371
Dominik Laskowski83b88212018-12-11 13:34:06 -08001372nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001373 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001374 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1375 return 0;
1376 }
1377
1378 const auto config = getHwComposer().getActiveConfig(*displayId);
1379 return config ? config->getVsyncPeriod() : 0;
1380}
1381
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001382void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1383 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001384 ATRACE_NAME("SF onVsync");
1385
Steven Thomas3cfac282017-02-06 12:29:30 -08001386 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001387 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001388 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001389 return;
1390 }
1391
Dominik Laskowski075d3172018-05-24 15:50:06 -07001392 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001393 return;
1394 }
1395
Dominik Laskowski075d3172018-05-24 15:50:06 -07001396 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001397 // For now, we don't do anything with external display vsyncs.
1398 return;
1399 }
1400
Alec Mourif8e689c2019-05-20 18:32:22 -07001401 bool periodFlushed = false;
1402 mScheduler->addResyncSample(timestamp, &periodFlushed);
1403 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001404 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001405 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001406}
1407
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001408void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001409 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1410 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001411}
1412
Ady Abraham261614e2019-07-10 17:53:12 -07001413bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001414 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001415}
1416
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001417void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001418 const auto display = getDefaultDisplayDeviceLocked();
1419 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001420 return;
1421 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001422 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001423
Ana Krulec7d1d6832018-12-27 11:10:09 -08001424 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001425 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1426 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001427
Dominik Laskowski22488f62019-03-28 09:53:04 -07001428 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001429 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1430 return;
1431 }
1432
Dominik Laskowski22488f62019-03-28 09:53:04 -07001433 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001434}
1435
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001436void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001437 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001438 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001439 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440
Lloyd Piqueba04e622017-12-14 17:11:26 -08001441 // Ignore events that do not have the right sequenceId.
1442 if (sequenceId != getBE().mComposerSequenceId) {
1443 return;
1444 }
1445
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 // Only lock if we're not on the main thread. This function is normally
1447 // called on a hwbinder thread, but for the primary display it's called on
1448 // the main thread with the state lock already held, so don't attempt to
1449 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001450 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001451
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001452 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001453
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001454 if (std::this_thread::get_id() == mMainThreadId) {
1455 // Process all pending hot plug events immediately if we are on the main thread.
1456 processDisplayHotplugEventsLocked();
1457 }
1458
Lloyd Piqueba04e622017-12-14 17:11:26 -08001459 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001460}
1461
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001462void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001463 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001464 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001465 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001466 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001467 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001468}
1469
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001470void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001471 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001472
1473 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1474 // display power state.
1475 postMessageAsync(new LambdaMessage(
1476 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1477}
1478
1479void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1480 ATRACE_CALL();
1481
Ady Abraham27c70212019-06-11 10:52:26 -07001482 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001484 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001485 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1486 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001487 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001488 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001489 }
Mathias Agopian86303202012-07-24 22:46:10 -07001490}
1491
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001492// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001493void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001494 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001495 // Clear the drawing state so that the logic inside of
1496 // handleTransactionLocked will fire. It will determine the delta between
1497 // mCurrentState and mDrawingState and re-apply all changes when we make the
1498 // transition.
1499 mDrawingState.displays.clear();
1500 mDisplays.clear();
1501}
1502
Steven Thomas050b2c82017-03-06 11:45:16 -08001503void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001504 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001505 if (!mVrFlinger)
1506 return;
1507 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001508 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001509 return;
1510 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001511
Lloyd Pique441d5042018-10-18 16:49:51 -07001512 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001513 ALOGE("Vr flinger is only supported for remote hardware composer"
1514 " service connections. Ignoring request to transition to vr"
1515 " flinger.");
1516 mVrFlingerRequestsDisplay = false;
1517 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001518 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001520 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001521
Steven Thomas0123ac62018-07-12 11:32:34 -07001522 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001523 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001524
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001525 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001526
1527 // Clear out all the output layers from the composition engine for all
1528 // displays before destroying the hardware composer interface. This ensures
1529 // any HWC layers are destroyed through that interface before it becomes
1530 // invalid.
1531 for (const auto& [token, displayDevice] : mDisplays) {
1532 displayDevice->getCompositionDisplay()->setOutputLayersOrderedByZ(
1533 compositionengine::Output::OutputLayers());
1534 }
1535
Steven Thomas0123ac62018-07-12 11:32:34 -07001536 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1537 // called below. Clear the reference now so we don't accidentally use it
1538 // later.
1539 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540
Steven Thomasb02664d2017-07-26 18:48:28 -07001541 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001546 // Delete the current instance before creating the new one
1547 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1548 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1549 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1550 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551
Lloyd Pique441d5042018-10-18 16:49:51 -07001552 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001553 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001554
1555 if (vrFlingerRequestsDisplay) {
1556 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001557 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001558
1559 mVisibleRegionsDirty = true;
1560 invalidateHwcGeometry();
1561
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001562 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001563 display = getDefaultDisplayDeviceLocked();
1564 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001565 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001566
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001568 const nsecs_t vsyncPeriod = getVsyncPeriod();
1569 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001570
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001571 // The present fences returned from vr_hwc are not an accurate
1572 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001573 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001574
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 // Use phase of 0 since phase is not known.
1576 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001577 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001578 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001579
Ana Krulecc2870422019-01-29 19:00:58 -08001580 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001581
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001582 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001583 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001584}
1585
Ady Abrahambe0f9482019-04-24 15:41:53 -07001586bool SurfaceFlinger::previousFrameMissed() NO_THREAD_SAFETY_ANALYSIS {
1587 // We are storing the last 2 present fences. If sf's phase offset is to be
1588 // woken up before the actual vsync but targeting the next vsync, we need to check
1589 // fence N-2
1590 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001591 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001592 ? mPreviousPresentFences[0]
1593 : mPreviousPresentFences[1];
1594
1595 return fence != Fence::NO_FENCE && (fence->getStatus() == Fence::Status::Unsignaled);
1596}
1597
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001598void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001599 DisplayStatInfo stats;
1600 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001601 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001602 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001603 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001604 mPhaseOffsets->getOffsetThresholdForNextVsync()
1605 ? presentTime
1606 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001607}
1608
Dominik Laskowski22488f62019-03-28 09:53:04 -07001609void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001610 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001611 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001612 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001613 // calculate the expected present time once and use the cached
1614 // value throughout this frame to make sure all layers are
1615 // seeing this same value.
1616 populateExpectedPresentTime();
1617
Ady Abraham50204dd2019-07-19 15:47:11 -07001618 const TracedOrdinal<bool> frameMissed = {"FrameMissed", previousFrameMissed()};
1619 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1620 mHadDeviceComposition && frameMissed};
1621 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1622 mHadClientComposition && frameMissed};
1623
Alec Mouricc0fc602019-02-26 21:45:19 -08001624 if (frameMissed) {
1625 mFrameMissedCount++;
1626 mTimeStats->incrementMissedFrames();
1627 }
1628
Alec Mouri40189b02019-03-05 15:07:54 -08001629 if (hwcFrameMissed) {
1630 mHwcFrameMissedCount++;
1631 }
1632
1633 if (gpuFrameMissed) {
1634 mGpuFrameMissedCount++;
1635 }
1636
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001637 if (mUseSmart90ForVideo) {
1638 // This call is made each time SF wakes up and creates a new frame. It is part
1639 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001640 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001641 }
1642
Ady Abrahamb838aed2019-02-12 15:30:16 -08001643 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001644 break;
1645 }
1646
Pete Bentleycc1ce642019-09-12 11:36:29 +00001647 // For now, only propagate backpressure when missing a hwc frame.
1648 if (hwcFrameMissed && !gpuFrameMissed) {
1649 if (mPropagateBackpressure) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001650 signalLayerUpdate();
1651 break;
1652 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001653 }
Dan Stoza50182882016-07-08 12:02:20 -07001654
Steven Thomas050b2c82017-03-06 11:45:16 -08001655 // Now that we're going to make it to the handleMessageTransaction()
1656 // call below it's safe to call updateVrFlinger(), which will
1657 // potentially trigger a display handoff.
1658 updateVrFlinger();
1659
Dan Stoza6b9454d2014-11-07 16:00:59 -08001660 bool refreshNeeded = handleMessageTransaction();
1661 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001662
1663 updateCursorAsync();
1664 updateInputFlinger();
1665
Dan Stoza58784442014-12-02 16:58:17 -08001666 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001667 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001668 // Signal a refresh if a transaction modified the window state,
1669 // a new buffer was latched, or if HWC has requested a full
1670 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001671 signalRefresh();
1672 }
1673 break;
1674 }
1675 case MessageQueue::REFRESH: {
1676 handleMessageRefresh();
1677 break;
1678 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001679 }
1680}
1681
Dan Stoza6b9454d2014-11-07 16:00:59 -08001682bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001683 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001684 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001685
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001686 bool flushedATransaction = flushTransactionQueues();
1687
1688 bool runHandleTransaction = transactionFlags &&
1689 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1690
1691 if (runHandleTransaction) {
1692 handleTransaction(eTransactionMask);
1693 } else {
1694 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001695 }
1696
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001697 if (transactionFlushNeeded()) {
1698 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001699 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001700
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001701 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001702}
1703
Mathias Agopian4fec8732012-06-29 14:12:52 -07001704void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001705 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001706
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001707 mRefreshPending = false;
1708
Lloyd Piqueab039b52019-02-13 14:22:42 -08001709 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001710 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001711 for (const auto& [_, display] : mDisplays) {
1712 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1713 }
1714 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1715 auto compositionLayer = layer->getCompositionLayer();
1716 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1717 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001718 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1719 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1720 auto compositionLayer = layer->getCompositionLayer();
1721 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1722 }
1723
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001724 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001725 refreshArgs.outputColorSetting = useColorManagement
1726 ? mDisplayColorSetting
1727 : compositionengine::OutputColorSetting::kUnmanaged;
1728 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1729 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001730
1731 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1732 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001733
1734 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1735 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1736 mDrawingState.colorMatrixChanged = false;
1737 }
1738
1739 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1740
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001741 if (mDebugRegion != 0) {
1742 refreshArgs.devOptFlashDirtyRegionsDelay =
1743 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1744 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001745
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001746 mGeometryInvalid = false;
1747
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001748 mCompositionEngine->present(refreshArgs);
1749
David Sodmanfa9b2af2017-12-24 13:28:59 -08001750 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001751 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001752
Lloyd Pique66d68602019-02-13 14:23:31 -08001753 mHadClientComposition =
1754 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1755 auto& displayDevice = tokenDisplayPair.second;
1756 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1757 });
1758 mHadDeviceComposition =
1759 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1760 auto& displayDevice = tokenDisplayPair.second;
1761 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1762 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001763
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001764 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001765
David Sodman7e4ae112018-02-09 15:02:28 -08001766 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001767 if (mVisibleRegionsDirty) {
1768 mVisibleRegionsDirty = false;
1769 if (mTracingEnabled) {
1770 mTracing.notify("visibleRegionsDirty");
1771 }
1772 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001773
1774 if (mCompositionEngine->needsAnotherUpdate()) {
1775 signalLayerUpdate();
1776 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001777}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001778
David Sodmanfa9b2af2017-12-24 13:28:59 -08001779
1780bool SurfaceFlinger::handleMessageInvalidate() {
1781 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001782 bool refreshNeeded = handlePageFlip();
1783
Vishnu Nair4351ad52019-02-11 14:13:02 -08001784 if (mVisibleRegionsDirty) {
1785 computeLayerBounds();
1786 }
1787
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001788 for (auto& layer : mLayersPendingRefresh) {
1789 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001790 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001791 invalidateLayerStack(layer, visibleReg);
1792 }
1793 mLayersPendingRefresh.clear();
1794 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001795}
1796
Ana Krulece588e312018-09-18 12:32:24 -07001797void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1798 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001799 // Update queue of past composite+present times and determine the
1800 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001801 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001802 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001803 while (!getBE().mCompositePresentTimes.empty()) {
1804 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001805 // Cached values should have been updated before calling this method,
1806 // which helps avoid duplicate syscalls.
1807 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1808 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1809 break;
1810 }
1811 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001812 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001813 }
1814
1815 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001816 while (getBE().mCompositePresentTimes.size() > 16) {
1817 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818 }
1819
Ana Krulece588e312018-09-18 12:32:24 -07001820 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001821}
1822
Ana Krulece588e312018-09-18 12:32:24 -07001823void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1824 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001825 // Integer division and modulo round toward 0 not -inf, so we need to
1826 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001827 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1828 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1829 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001830
Ana Krulec757f63a2019-01-25 10:46:18 -08001831 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001832 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001833 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001834 }
1835
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001836 // Snap the latency to a value that removes scheduling jitter from the
1837 // composition and present times, which often have >1ms of jitter.
1838 // Reducing jitter is important if an app attempts to extrapolate
1839 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001840 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001841 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001842 nsecs_t bias = stats.vsyncPeriod / 2;
1843 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1844 nsecs_t snappedCompositeToPresentLatency =
1845 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001846
David Sodman99974d22017-11-28 12:04:33 -08001847 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001848 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1849 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001850 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851}
1852
David Sodman2b406362017-12-15 13:33:47 -08001853void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001854{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001855 ATRACE_CALL();
1856 ALOGV("postComposition");
1857
Brian Anderson3546a3f2016-07-14 11:51:14 -07001858 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001859 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001860 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001861 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001862 }
1863
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001864 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001865 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001866
David Sodman73beded2017-11-15 11:56:06 -08001867 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001868 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001869 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001870 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001871 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1872 ->getRenderSurface()
1873 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001874 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001875 } else {
1876 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1877 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001878
David Sodman73beded2017-11-15 11:56:06 -08001879 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001880 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1881 mPreviousPresentFences[0] = displayDevice
1882 ? getHwComposer().getPresentFence(*displayDevice->getId())
1883 : Fence::NO_FENCE;
1884 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001885 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001886
Ana Krulece588e312018-09-18 12:32:24 -07001887 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001888 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001889
Lloyd Piqueab039b52019-02-13 14:22:42 -08001890 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1891 // be sampled a little later than when we started doing work for this frame,
1892 // but that should be okay since updateCompositorTiming has snapping logic.
1893 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1894 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001895 CompositorTiming compositorTiming;
1896 {
David Sodman99974d22017-11-28 12:04:33 -08001897 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1898 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001899 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001900
Robert Carr2047fae2016-11-28 14:09:09 -08001901 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001902 bool frameLatched =
1903 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1904 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001905 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001906 recordBufferingStats(layer->getName().string(),
1907 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001908 }
Robert Carr2047fae2016-11-28 14:09:09 -08001909 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001910
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001911 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001912 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001913 }
1914
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001915 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001916 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1917 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001918 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001919 }
1920 }
1921
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001922 if (mAnimCompositionPending) {
1923 mAnimCompositionPending = false;
1924
Brian Anderson4e606e32017-03-16 15:34:57 -07001925 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001926 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001927 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001928 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001929 // The HWC doesn't support present fences, so use the refresh
1930 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001931 const nsecs_t presentTime =
1932 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001933 mAnimFrameTracker.setActualPresentTime(presentTime);
1934 }
1935 mAnimFrameTracker.advanceFrame();
1936 }
Dan Stozab90cf072015-03-05 11:05:59 -08001937
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001938 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001939 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001940 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001941 }
1942
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001943 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001944
Lloyd Pique32cbe282018-10-19 13:09:22 -07001945 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1946 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001947 return;
1948 }
1949
1950 nsecs_t currentTime = systemTime();
1951 if (mHasPoweredOff) {
1952 mHasPoweredOff = false;
1953 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001954 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001955 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001956 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1957 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001958 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001959 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001960 }
David Sodman4a36e932017-11-07 14:29:47 -08001961 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001962 }
David Sodman4a36e932017-11-07 14:29:47 -08001963 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001964
1965 {
1966 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001967 if (mTexturePool.size() < mTexturePoolSize) {
1968 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001969 const size_t offset = mTexturePool.size();
1970 mTexturePool.resize(mTexturePoolSize);
1971 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1972 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001973 } else if (mTexturePool.size() > mTexturePoolSize) {
1974 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1975 const size_t offset = mTexturePoolSize;
1976 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1977 mTexturePool.resize(mTexturePoolSize);
1978 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001979 }
1980 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001981
Ady Abrahambe0f9482019-04-24 15:41:53 -07001982 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001983 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001984
Kevin DuBois413287f2019-02-25 08:46:47 -08001985 if (mLumaSampling && mRegionSamplingThread) {
1986 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001987 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07001988
1989 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
1990 // side-effect of getTotalSize(), so we check that again here
1991 if (ATRACE_ENABLED()) {
1992 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
1993 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994}
1995
Vishnu Nair4351ad52019-02-11 14:13:02 -08001996void SurfaceFlinger::computeLayerBounds() {
1997 for (const auto& pair : mDisplays) {
1998 const auto& displayDevice = pair.second;
1999 const auto display = displayDevice->getCompositionDisplay();
2000 for (const auto& layer : mDrawingState.layersSortedByZ) {
2001 // only consider the layers on the given layer stack
2002 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002003 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002004 }
2005
2006 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2007 }
2008 }
2009}
2010
David Sodmanfa9b2af2017-12-24 13:28:59 -08002011void SurfaceFlinger::postFrame()
2012{
2013 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002014 const auto display = getDefaultDisplayDeviceLocked();
2015 if (display && getHwComposer().isConnected(*display->getId())) {
2016 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002017 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2018 logFrameStats();
2019 }
2020 }
2021}
2022
Mathias Agopian87baae12012-07-31 12:38:26 -07002023void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002024{
Mathias Agopian841cde52012-03-01 15:44:37 -08002025 ATRACE_CALL();
2026
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002027 // here we keep a copy of the drawing state (that is the state that's
2028 // going to be overwritten by handleTransactionLocked()) outside of
2029 // mStateLock so that the side-effects of the State assignment
2030 // don't happen with mStateLock held (which can cause deadlocks).
2031 State drawingState(mDrawingState);
2032
Mathias Agopianca4d3602011-05-19 15:38:14 -07002033 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002034 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002035
Mathias Agopianca4d3602011-05-19 15:38:14 -07002036 // Here we're guaranteed that some transaction flags are set
2037 // so we can call handleTransactionLocked() unconditionally.
2038 // We call getTransactionFlags(), which will also clear the flags,
2039 // with mStateLock held to guarantee that mCurrentState won't change
2040 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002041
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002042 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002043 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002044 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002045
Mathias Agopianca4d3602011-05-19 15:38:14 -07002046 mDebugInTransaction = 0;
2047 invalidateHwcGeometry();
2048 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002049}
2050
Lloyd Piqueba04e622017-12-14 17:11:26 -08002051void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2052 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002053 const std::optional<DisplayIdentificationInfo> info =
2054 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002055
Dominik Laskowski075d3172018-05-24 15:50:06 -07002056 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002057 continue;
2058 }
2059
Lloyd Piqueba04e622017-12-14 17:11:26 -08002060 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002061 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002062 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002063 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2064 initScheduler(info->id);
2065 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002066 mPhysicalDisplayTokens[info->id] = new BBinder();
2067 DisplayDeviceState state;
2068 state.displayId = info->id;
2069 state.isSecure = true; // All physical displays are currently considered secure.
2070 state.displayName = info->name;
2071 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2072 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002073 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002074 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002075 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002076
Dominik Laskowski075d3172018-05-24 15:50:06 -07002077 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2078 if (index >= 0) {
2079 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2080 mInterceptor->saveDisplayDeletion(state.sequenceId);
2081 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002082 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002083 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002084 }
2085
2086 processDisplayChangesLocked();
2087 }
2088
2089 mPendingHotplugEvents.clear();
2090}
2091
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002092void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002093 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2094 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002095}
2096
Lloyd Pique99d3da52018-01-22 17:48:03 -08002097sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002098 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002099 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002100 const sp<IGraphicBufferProducer>& producer) {
2101 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002102 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002103 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002104 creationArgs.isSecure = state.isSecure;
2105 creationArgs.displaySurface = dispSurface;
2106 creationArgs.hasWideColorGamut = false;
2107 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002108 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002109
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002110 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002111 creationArgs.isPrimary = isInternalDisplay;
2112
2113 if (useColorManagement && displayId) {
2114 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002115 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002116 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002117 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002118 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002119
Dominik Laskowski7e045462018-05-30 13:02:02 -07002120 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002121 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002122 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002123 }
tangrobin6753a022018-08-10 10:58:54 +08002124 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002125
Dominik Laskowski075d3172018-05-24 15:50:06 -07002126 if (displayId) {
2127 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002128 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002129 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002130 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002131
Lloyd Pique90c115d2018-09-18 21:39:42 -07002132 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002133 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002134 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002135
Lloyd Pique99d3da52018-01-22 17:48:03 -08002136 // Make sure that composition can never be stalled by a virtual display
2137 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002138 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002139 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002140 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2141 }
2142
Dominik Laskowski075d3172018-05-24 15:50:06 -07002143 creationArgs.displayInstallOrientation =
2144 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002145
Lloyd Pique99d3da52018-01-22 17:48:03 -08002146 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002147 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002148
Lloyd Pique90c115d2018-09-18 21:39:42 -07002149 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002150
2151 if (maxFrameBufferAcquiredBuffers >= 3) {
2152 nativeWindowSurface->preallocateBuffers();
2153 }
2154
2155 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002156 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002157 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002158 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002159 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002160 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002161 display->getCompositionDisplay()->setColorProfile(
2162 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2163 RenderIntent::COLORIMETRIC,
2164 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002165 if (!state.isVirtual()) {
2166 LOG_ALWAYS_FATAL_IF(!displayId);
2167 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002168 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002170 display->setLayerStack(state.layerStack);
2171 display->setProjection(state.orientation, state.viewport, state.frame);
2172 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002173
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002174 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002175}
2176
Lloyd Pique347200f2017-12-14 17:00:15 -08002177void SurfaceFlinger::processDisplayChangesLocked() {
2178 // here we take advantage of Vector's copy-on-write semantics to
2179 // improve performance by skipping the transaction entirely when
2180 // know that the lists are identical
2181 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2182 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2183 if (!curr.isIdenticalTo(draw)) {
2184 mVisibleRegionsDirty = true;
2185 const size_t cc = curr.size();
2186 size_t dc = draw.size();
2187
2188 // find the displays that were removed
2189 // (ie: in drawing state but not in current state)
2190 // also handle displays that changed
2191 // (ie: displays that are in both lists)
2192 for (size_t i = 0; i < dc;) {
2193 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2194 if (j < 0) {
2195 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002196 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002197 // Save display ID before disconnecting.
2198 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002199 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002200
2201 if (!display->isVirtual()) {
2202 LOG_ALWAYS_FATAL_IF(!displayId);
2203 dispatchDisplayHotplugEvent(displayId->value, false);
2204 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002205 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002206
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002207 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002208 } else {
2209 // this display is in both lists. see if something changed.
2210 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002211 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002212 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2213 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2214 if (state_binder != draw_binder) {
2215 // changing the surface is like destroying and
2216 // recreating the DisplayDevice, so we just remove it
2217 // from the drawing state, so that it get re-added
2218 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002219 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002220 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002221 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002222 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002223 mDrawingState.displays.removeItemsAt(i);
2224 dc--;
2225 // at this point we must loop to the next item
2226 continue;
2227 }
2228
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002230 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002231 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002232 }
2233 if ((state.orientation != draw[i].orientation) ||
2234 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002235 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002236 }
2237 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002238 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002239 }
2240 }
2241 }
2242 ++i;
2243 }
2244
2245 // find displays that were added
2246 // (ie: in current state but not in drawing state)
2247 for (size_t i = 0; i < cc; i++) {
2248 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2249 const DisplayDeviceState& state(curr[i]);
2250
Lloyd Pique542307f2018-10-19 13:24:08 -07002251 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002252 sp<IGraphicBufferProducer> producer;
2253 sp<IGraphicBufferProducer> bqProducer;
2254 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002255 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002256
Dominik Laskowski075d3172018-05-24 15:50:06 -07002257 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002258 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002259 // Virtual displays without a surface are dormant:
2260 // they have external state (layer stack, projection,
2261 // etc.) but no internal state (i.e. a DisplayDevice).
2262 if (state.surface != nullptr) {
2263 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002264 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002265 int width = 0;
2266 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2267 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2268 int height = 0;
2269 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2270 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2271 int intFormat = 0;
2272 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2273 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002274 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002275
Dominik Laskowski075d3172018-05-24 15:50:06 -07002276 displayId =
2277 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002278 }
2279
2280 // TODO: Plumb requested format back up to consumer
2281
2282 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002283 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002284 bqProducer, bqConsumer,
2285 state.displayName);
2286
2287 dispSurface = vds;
2288 producer = vds;
2289 }
2290 } else {
2291 ALOGE_IF(state.surface != nullptr,
2292 "adding a supported display, but rendering "
2293 "surface is provided (%p), ignoring it",
2294 state.surface.get());
2295
Dominik Laskowski075d3172018-05-24 15:50:06 -07002296 displayId = state.displayId;
2297 LOG_ALWAYS_FATAL_IF(!displayId);
2298 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002299 producer = bqProducer;
2300 }
2301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002303 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002304 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002305 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002306 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002307 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002308 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002309 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002310 }
2311 }
2312 }
2313 }
2314 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002315
2316 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002317}
2318
Mathias Agopian87baae12012-07-31 12:38:26 -07002319void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002320{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002321 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2322
Dan Stoza7dde5992015-05-22 09:51:44 -07002323 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002324 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2325 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002326 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002328 /*
2329 * Traversal of the children
2330 * (perform the transaction for each of them if needed)
2331 */
2332
Marissa Wall06255332019-03-27 13:48:27 -07002333 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002334 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002336 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337
2338 const uint32_t flags = layer->doTransaction(0);
2339 if (flags & Layer::eVisibleRegion)
2340 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002341
2342 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002343 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002344 }
Robert Carr2047fae2016-11-28 14:09:09 -08002345 });
Marissa Wall06255332019-03-27 13:48:27 -07002346 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 }
2348
2349 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002350 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351 */
2352
Mathias Agopiane57f2922012-08-09 16:29:12 -07002353 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002355 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002356 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002358 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002359 // The transform hint might have changed for some layers
2360 // (either because a display has changed, or because a layer
2361 // as changed).
2362 //
2363 // Walk through all the layers in currentLayers,
2364 // and update their transform hint.
2365 //
2366 // If a layer is visible only on a single display, then that
2367 // display is used to calculate the hint, otherwise we use the
2368 // default display.
2369 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002370 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002371 // the hint is set before we acquire a buffer from the surface texture.
2372 //
2373 // NOTE: layer transactions have taken place already, so we use their
2374 // drawing state. However, SurfaceFlinger's own transaction has not
2375 // happened yet, so we must use the current state layer list
2376 // (soon to become the drawing state list).
2377 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002378 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002379 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002380 bool first = true;
2381 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002382 // NOTE: we rely on the fact that layers are sorted by
2383 // layerStack first (so we don't have to traverse the list
2384 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002385 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002386 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002387 currentlayerStack = layerStack;
2388 // figure out if this layerstack is mirrored
2389 // (more than one display) if so, pick the default display,
2390 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002391 hintDisplay = nullptr;
2392 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002393 if (display->getCompositionDisplay()
2394 ->belongsInOutput(layer->getLayerStack(),
2395 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002396 if (hintDisplay) {
2397 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002398 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002399 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002400 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002401 }
2402 }
2403 }
2404 }
Chet Haase91d25932013-04-11 15:24:55 -07002405
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002406 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002407 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2408 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002409
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002410 // could be null when this layer is using a layerStack
2411 // that is not visible on any display. Also can occur at
2412 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002413 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002414 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002415
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002416 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002417 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002418 if (hintDisplay) {
2419 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002420 }
Robert Carr2047fae2016-11-28 14:09:09 -08002421
2422 first = false;
2423 });
Mathias Agopian84300952012-11-21 16:02:13 -08002424 }
2425
2426
Mathias Agopian3559b072012-08-15 13:46:03 -07002427 /*
2428 * Perform our own transaction if needed
2429 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002430
2431 if (mLayersAdded) {
2432 mLayersAdded = false;
2433 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002434 mVisibleRegionsDirty = true;
2435 }
2436
2437 // some layers might have been removed, so
2438 // we need to update the regions they're exposing.
2439 if (mLayersRemoved) {
2440 mLayersRemoved = false;
2441 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002442 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002443 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002444 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002445 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002446 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002447 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002448 }
Robert Carr2047fae2016-11-28 14:09:09 -08002449 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002450 }
2451
Vishnu Nairec0ab382019-02-13 15:32:56 -08002452 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002454}
2455
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002456void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002457 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002458 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002459 return;
2460 }
2461
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002462 if (mVisibleRegionsDirty || mInputInfoChanged) {
2463 mInputInfoChanged = false;
2464 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002465 } else if (mInputWindowCommands.syncInputWindows) {
2466 // If the caller requested to sync input windows, but there are no
2467 // changes to input windows, notify immediately.
2468 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002469 }
2470
2471 executeInputWindowCommands();
2472}
2473
2474void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002475 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002476
2477 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2478 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002479 // When calculating the screen bounds we ignore the transparent region since it may
2480 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002481 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002482 }
2483 });
chaviw291d88a2019-02-14 10:33:58 -08002484
2485 mInputFlinger->setInputWindows(inputHandles,
2486 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2487 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002488}
2489
Vishnu Nairec0ab382019-02-13 15:32:56 -08002490void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002491 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002492 mPendingInputWindowCommands.clear();
2493}
2494
chaviwfbe5d9c2018-12-26 12:23:37 -08002495void SurfaceFlinger::executeInputWindowCommands() {
chaviwfbe5d9c2018-12-26 12:23:37 -08002496 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2497 if (transferTouchFocusCommand.fromToken != nullptr &&
2498 transferTouchFocusCommand.toToken != nullptr &&
2499 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2500 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2501 transferTouchFocusCommand.toToken);
2502 }
2503 }
2504
2505 mInputWindowCommands.clear();
2506}
2507
Riley Andrews03414a12014-07-01 14:22:59 -07002508void SurfaceFlinger::updateCursorAsync()
2509{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002510 compositionengine::CompositionRefreshArgs refreshArgs;
2511 for (const auto& [_, display] : mDisplays) {
2512 if (display->getId()) {
2513 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002514 }
2515 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002516
2517 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002518}
2519
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002520void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2521 if (mScheduler) {
2522 // In practice it's not allowed to hotplug in/out the primary display once it's been
2523 // connected during startup, but some tests do it, so just warn and return.
2524 ALOGW("Can't re-init scheduler");
2525 return;
2526 }
2527
2528 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2529 mRefreshRateConfigs =
2530 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2531 getHwComposer().getConfigs(
2532 primaryDisplayId),
2533 currentConfig);
2534 mRefreshRateStats =
2535 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2536 currentConfig, HWC_POWER_MODE_OFF);
2537 mRefreshRateStats->setConfigMode(currentConfig);
2538
2539 // start the EventThread
2540 mScheduler =
2541 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2542 *mRefreshRateConfigs);
2543 mAppConnectionHandle =
2544 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2545 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2546 impl::EventThread::InterceptVSyncsCallback());
2547 mSfConnectionHandle =
2548 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2549 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2550 [this](nsecs_t timestamp) {
2551 mInterceptor->saveVSyncEvent(timestamp);
2552 });
2553
2554 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2555 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2556 mPhaseOffsets->getCurrentOffsets());
2557
2558 mRegionSamplingThread =
2559 new RegionSamplingThread(*this, *mScheduler,
2560 RegionSamplingThread::EnvironmentTimingTunables());
2561
2562 mScheduler->setChangeRefreshRateCallback(
2563 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2564 Mutex::Autolock lock(mStateLock);
2565 setRefreshRateTo(type, event);
2566 });
2567}
2568
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569void SurfaceFlinger::commitTransaction()
2570{
Nataniel Borges2b796da2019-02-15 13:32:18 -08002571 withTracingLock([&]() {
Vishnu Nair0f085c62019-08-30 08:49:12 -07002572 if (!mLayersPendingRemoval.isEmpty()) {
2573 // Notify removed layers now that they can't be drawn from
2574 for (const auto& l : mLayersPendingRemoval) {
2575 recordBufferingStats(l->getName().string(), l->getOccupancyHistory(true));
2576
2577 // Ensure any buffers set to display on any children are released.
2578 if (l->isRemovedFromCurrentState()) {
2579 l->latchAndReleaseBuffer();
2580 }
2581
2582 // If the layer has been removed and has no parent, then it will not be reachable
2583 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2584 // ensure we can copy its current to drawing state.
2585 if (!l->getParent()) {
2586 mOffscreenLayers.emplace(l.get());
2587 }
2588 }
2589 mLayersPendingRemoval.clear();
2590 }
2591
2592 // If this transaction is part of a window animation then the next frame
2593 // we composite should be considered an animation as well.
2594 mAnimCompositionPending = mAnimTransactionPending;
2595
Nataniel Borges2b796da2019-02-15 13:32:18 -08002596 mDrawingState = mCurrentState;
2597 // clear the "changed" flags in current state
2598 mCurrentState.colorMatrixChanged = false;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002599
chaviw74d90ad2019-04-26 14:45:26 -07002600 mDrawingState.traverseInZOrder([&](Layer* layer) {
2601 layer->commitChildList();
2602
2603 // If the layer can be reached when traversing mDrawingState, then the layer is no
2604 // longer offscreen. Remove the layer from the offscreenLayer set.
2605 if (mOffscreenLayers.count(layer)) {
2606 mOffscreenLayers.erase(layer);
2607 }
2608 });
2609
2610 commitOffscreenLayers();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002611 });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002612
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002613 mTransactionPending = false;
2614 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002615 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616}
2617
Nataniel Borges2b796da2019-02-15 13:32:18 -08002618void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2619 if (mTracingEnabledChanged) {
2620 mTracingEnabled = mTracing.isEnabled();
2621 mTracingEnabledChanged = false;
2622 }
2623
2624 // Synchronize with Tracing thread
2625 std::unique_lock<std::mutex> lock;
2626 if (mTracingEnabled) {
2627 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2628 }
2629
2630 lockedOperation();
2631
2632 // Synchronize with Tracing thread
2633 if (mTracingEnabled) {
2634 lock.unlock();
2635 }
2636}
2637
chaviw74d90ad2019-04-26 14:45:26 -07002638void SurfaceFlinger::commitOffscreenLayers() {
2639 for (Layer* offscreenLayer : mOffscreenLayers) {
2640 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2641 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2642 if (!trFlags) return;
2643
2644 layer->doTransaction(0);
2645 layer->commitChildList();
2646 });
2647 }
2648}
2649
Chia-I Wuab0c3192017-08-01 11:29:00 -07002650void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002651 for (const auto& [token, displayDevice] : mDisplays) {
2652 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002653 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002654 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002655 }
2656 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002657}
2658
Dan Stoza6b9454d2014-11-07 16:00:59 -08002659bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660{
Ady Abraham09bd3922019-04-08 10:44:56 -07002661 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002662 ALOGV("handlePageFlip");
2663
Brian Andersond6927fb2016-07-23 23:37:30 -07002664 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002665
Mathias Agopian4fec8732012-06-29 14:12:52 -07002666 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002667 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002668 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002669
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002670 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2671
Eric Penner51c59cd2014-07-28 19:51:58 -07002672 // Store the set of layers that need updates. This set must not change as
2673 // buffers are being latched, as this could result in a deadlock.
2674 // Example: Two producers share the same command stream and:
2675 // 1.) Layer 0 is latched
2676 // 2.) Layer 0 gets a new frame
2677 // 2.) Layer 1 gets a new frame
2678 // 3.) Layer 1 is latched.
2679 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2680 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002681 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002682 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002683 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002684 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002685 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002686 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002687 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002688 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002689 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002690 } else {
2691 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002692 }
Robert Carr2047fae2016-11-28 14:09:09 -08002693 });
2694
chaviw49a108c2019-08-12 11:23:06 -07002695 // The client can continue submitting buffers for offscreen layers, but they will not
2696 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2697 // layers to ensure dequeueBuffer doesn't block indefinitely.
2698 for (Layer* offscreenLayer : mOffscreenLayers) {
2699 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2700 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2701 }
2702
Lloyd Piquef2c79392018-12-20 16:23:33 -08002703 if (!mLayersWithQueuedFrames.empty()) {
2704 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2705 // writes to Layer current state. See also b/119481871
2706 Mutex::Autolock lock(mStateLock);
2707
2708 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002709 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002710 mLayersPendingRefresh.push_back(layer);
2711 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002712 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002713 if (layer->isBufferLatched()) {
2714 newDataLatched = true;
2715 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002716 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002717 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002718
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002719 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002720
2721 // If we will need to wake up at some time in the future to deal with a
2722 // queued frame that shouldn't be displayed during this vsync period, wake
2723 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002724 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002725 signalLayerUpdate();
2726 }
2727
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002728 // enter boot animation on first buffer latch
2729 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2730 ALOGI("Enter boot animation");
2731 mBootStage = BootStage::BOOTANIMATION;
2732 }
2733
Dan Stoza6b9454d2014-11-07 16:00:59 -08002734 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002735 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736}
2737
Mathias Agopianad456f92011-01-13 17:53:01 -08002738void SurfaceFlinger::invalidateHwcGeometry()
2739{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002741}
2742
Robert Carrc0df3122019-04-11 13:18:21 -07002743status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2744 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2745 const sp<IBinder>& parentHandle,
2746 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002747 // add this layer to the current state list
2748 {
2749 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002750 sp<Layer> parent;
2751 if (parentHandle != nullptr) {
2752 parent = fromHandle(parentHandle);
2753 if (parent == nullptr) {
2754 return NAME_NOT_FOUND;
2755 }
2756 } else {
2757 parent = parentLayer;
2758 }
2759
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002761 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002762 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002763 return NO_MEMORY;
2764 }
Robert Carrc0df3122019-04-11 13:18:21 -07002765
2766 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2767
Robert Carrb89ea9d2018-12-10 13:01:14 -08002768 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002769 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002770 } else if (parent == nullptr) {
2771 lbc->onRemovedFromCurrentState();
2772 } else if (parent->isRemovedFromCurrentState()) {
2773 parent->addChild(lbc);
2774 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002775 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002776 parent->addChild(lbc);
2777 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002778
Yiwei Zhang243b3782018-05-15 17:40:04 -07002779 if (gbc != nullptr) {
2780 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2781 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2782 mMaxGraphicBufferProducerListSize,
2783 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2784 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002785 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002786 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002787 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002788 }
2789
Mathias Agopian96f08192010-06-02 23:28:45 -07002790 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002791 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002792
Dan Stoza7d89d062015-04-30 13:29:25 -07002793 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002794}
2795
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002796uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002797 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002798}
2799
Mathias Agopian3f844832013-08-07 21:24:32 -07002800uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002801 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802}
2803
Mathias Agopian3f844832013-08-07 21:24:32 -07002804uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002805 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002806}
2807
2808uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002809 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002810 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002811 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002813 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 }
2815 return old;
2816}
2817
Marissa Wall713b63f2018-10-17 15:42:43 -07002818bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002819 // to prevent onHandleDestroyed from being called while the lock is held,
2820 // we must keep a copy of the transactions (specifically the composer
2821 // states) around outside the scope of the lock
2822 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002823 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002824 {
2825 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002826
Valerie Haufce31b82019-04-30 16:41:14 -07002827 auto it = mTransactionQueues.begin();
2828 while (it != mTransactionQueues.end()) {
2829 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002830
Valerie Haufce31b82019-04-30 16:41:14 -07002831 while (!transactionQueue.empty()) {
2832 const auto& transaction = transactionQueue.front();
2833 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002834 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002835 transaction.states)) {
2836 setTransactionFlags(eTransactionFlushNeeded);
2837 break;
2838 }
2839 transactions.push_back(transaction);
2840 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2841 mPendingInputWindowCommands, transaction.desiredPresentTime,
2842 transaction.buffer, transaction.callback,
2843 transaction.postTime, transaction.privileged,
2844 /*isMainThread*/ true);
2845 transactionQueue.pop();
2846 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002847 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002848
Valerie Haufce31b82019-04-30 16:41:14 -07002849 if (transactionQueue.empty()) {
2850 it = mTransactionQueues.erase(it);
2851 mTransactionCV.broadcast();
2852 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002853 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002854 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002855 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002856 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002857 return flushedATransaction;
2858}
2859
2860bool SurfaceFlinger::transactionFlushNeeded() {
2861 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002862}
2863
chaviwca27f252018-02-06 16:46:39 -08002864
Marissa Wall17b4e452018-12-26 16:32:34 -08002865bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002866 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002867 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002868 if (!useCachedExpectedPresentTime)
2869 populateExpectedPresentTime();
2870
2871 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002872 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2873 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2874 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2875 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2876 return false;
2877 }
2878
Marissa Wall713b63f2018-10-17 15:42:43 -07002879 for (const ComposerState& state : states) {
2880 const layer_state_t& s = state.state;
2881 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2882 continue;
2883 }
2884 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002885 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002886 }
2887 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002888 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002889}
2890
2891void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
2892 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08002893 const sp<IBinder>& applyToken,
Marissa Wall17b4e452018-12-26 16:32:34 -08002894 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07002895 int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07002896 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07002897 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002898 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002899
Valerie Haubc6ddb12019-03-08 11:10:15 -08002900 const int64_t postTime = systemTime();
2901
Robert Carr14167e02019-02-13 13:50:55 -08002902 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2903
Mathias Agopian698c0872011-06-28 19:09:31 -07002904 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002905
Marissa Wall713b63f2018-10-17 15:42:43 -07002906 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002907 auto itr = mTransactionQueues.find(applyToken);
2908 // if this is an animation frame, wait until prior animation frame has
2909 // been applied by SF
2910 if (flags & eAnimation) {
2911 while (itr != mTransactionQueues.end()) {
2912 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2913 if (CC_UNLIKELY(err != NO_ERROR)) {
2914 ALOGW_IF(err == TIMED_OUT,
2915 "setTransactionState timed out "
2916 "waiting for animation frame to apply");
2917 break;
2918 }
2919 itr = mTransactionQueues.find(applyToken);
2920 }
2921 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002922
2923 // Expected present time is computed and cached on invalidate, so it may be stale.
2924 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2925 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002926 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07002927 uncacheBuffer, listenerCallbacks, postTime,
2928 privileged);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002929 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002930 return;
2931 }
2932
Valerie Haubc6ddb12019-03-08 11:10:15 -08002933 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Marissa Wall3dad52d2019-03-22 14:03:19 -07002934 uncacheBuffer, listenerCallbacks, postTime, privileged);
Marissa Wall713b63f2018-10-17 15:42:43 -07002935}
2936
2937void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08002938 const Vector<DisplayState>& displays, uint32_t flags,
Robert Carr14167e02019-02-13 13:50:55 -08002939 const InputWindowCommands& inputWindowCommands,
Marissa Wall78b72202019-03-15 14:58:34 -07002940 const int64_t desiredPresentTime,
Marissa Wall947d34e2019-03-29 14:03:53 -07002941 const client_cache_t& uncacheBuffer,
Marissa Wall3dad52d2019-03-22 14:03:19 -07002942 const std::vector<ListenerCallbacks>& listenerCallbacks,
Marissa Wall78b72202019-03-15 14:58:34 -07002943 const int64_t postTime, bool privileged,
2944 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002945 uint32_t transactionFlags = 0;
2946
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002947 if (flags & eAnimation) {
2948 // For window updates that are part of an animation we must wait for
2949 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002950 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002951 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002952 if (CC_UNLIKELY(err != NO_ERROR)) {
2953 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002954 // caller after a few seconds.
2955 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2956 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002957 mAnimTransactionPending = false;
2958 break;
2959 }
2960 }
2961 }
2962
chaviwca27f252018-02-06 16:46:39 -08002963 for (const DisplayState& display : displays) {
2964 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002965 }
2966
Marissa Walld600d572019-03-26 15:38:50 -07002967 // In case the client has sent a Transaction that should receive callbacks but without any
2968 // SurfaceControls that should be included in the callback, send the listener and callbackIds
2969 // to the callback thread so it can send an empty callback
2970 if (!listenerCallbacks.empty()) {
2971 mTransactionCompletedThread.run();
2972 }
Marissa Wallefb71af2019-06-27 14:45:53 -07002973 for (const auto& listenerCallback : listenerCallbacks) {
2974 mTransactionCompletedThread.startRegistration(listenerCallback);
Marissa Walld600d572019-03-26 15:38:50 -07002975 }
2976
Marissa Walle2ffb422018-10-12 11:33:52 -07002977 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002978 for (const ComposerState& state : states) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07002979 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, listenerCallbacks,
2980 postTime, privileged);
2981 }
2982
Marissa Wallefb71af2019-06-27 14:45:53 -07002983 for (const auto& listenerCallback : listenerCallbacks) {
2984 mTransactionCompletedThread.endRegistration(listenerCallback);
2985 }
2986
Marissa Walle2ffb422018-10-12 11:33:52 -07002987 // If the state doesn't require a traversal and there are callbacks, send them now
Marissa Wallb0022cc2019-04-16 14:19:55 -07002988 if (!(clientStateFlags & eTraversalNeeded) && !listenerCallbacks.empty()) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002989 mTransactionCompletedThread.sendCallbacks();
2990 }
2991 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002992
chaviw273171b2018-12-26 11:46:30 -08002993 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2994
Marissa Wall947d34e2019-03-29 14:03:53 -07002995 if (uncacheBuffer.isValid()) {
2996 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002997 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002998 }
2999
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003000 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3001 // anyway. This can be used as a flush mechanism for previous async transactions.
3002 // Empty animation transaction can be used to simulate back-pressure, so also force a
3003 // transaction for empty animation transactions.
3004 if (transactionFlags == 0 &&
3005 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003006 transactionFlags = eTransactionNeeded;
3007 }
3008
Marissa Wall06255332019-03-27 13:48:27 -07003009 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3010 // so we don't have to wake up again next frame to preform an uneeded traversal.
3011 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3012 transactionFlags = transactionFlags & (~eTraversalNeeded);
3013 mTraversalNeededMainThread = true;
3014 }
3015
Mathias Agopian386aa982011-11-07 21:58:03 -08003016 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003017 if (mInterceptor->isEnabled()) {
3018 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003019 }
Irvel468051e2016-06-13 16:44:44 -07003020
Mathias Agopian386aa982011-11-07 21:58:03 -08003021 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003022 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3023 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003024 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003025
3026 // if this is a synchronous transaction, wait for it to take effect
3027 // before returning.
3028 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003029 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003030 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003031 if (flags & eAnimation) {
3032 mAnimTransactionPending = true;
3033 }
chaviw4fe36852019-04-15 16:25:49 -07003034 if (mPendingInputWindowCommands.syncInputWindows) {
3035 mPendingSyncInputWindows = true;
3036 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003037
3038 // applyTransactionState can be called by either the main SF thread or by
3039 // another process through setTransactionState. While a given process may wish
3040 // to wait on synchronous transactions, the main SF thread should never
3041 // be blocked. Therefore, we only wait if isMainThread is false.
3042 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003043 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3044 if (CC_UNLIKELY(err != NO_ERROR)) {
3045 // just in case something goes wrong in SF, return to the
3046 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003047 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3048 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003049 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003050 break;
3051 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053 }
3054}
3055
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003056uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3057 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3058 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003059
Mathias Agopiane57f2922012-08-09 16:29:12 -07003060 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003061 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3062
3063 const uint32_t what = s.what;
3064 if (what & DisplayState::eSurfaceChanged) {
3065 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3066 state.surface = s.surface;
3067 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003068 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003069 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003070 if (what & DisplayState::eLayerStackChanged) {
3071 if (state.layerStack != s.layerStack) {
3072 state.layerStack = s.layerStack;
3073 flags |= eDisplayTransactionNeeded;
3074 }
3075 }
3076 if (what & DisplayState::eDisplayProjectionChanged) {
3077 if (state.orientation != s.orientation) {
3078 state.orientation = s.orientation;
3079 flags |= eDisplayTransactionNeeded;
3080 }
3081 if (state.frame != s.frame) {
3082 state.frame = s.frame;
3083 flags |= eDisplayTransactionNeeded;
3084 }
3085 if (state.viewport != s.viewport) {
3086 state.viewport = s.viewport;
3087 flags |= eDisplayTransactionNeeded;
3088 }
3089 }
3090 if (what & DisplayState::eDisplaySizeChanged) {
3091 if (state.width != s.width) {
3092 state.width = s.width;
3093 flags |= eDisplayTransactionNeeded;
3094 }
3095 if (state.height != s.height) {
3096 state.height = s.height;
3097 flags |= eDisplayTransactionNeeded;
3098 }
3099 }
3100
Mathias Agopiane57f2922012-08-09 16:29:12 -07003101 return flags;
3102}
3103
Robert Carr14167e02019-02-13 13:50:55 -08003104bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003105 IPCThreadState* ipc = IPCThreadState::self();
3106 const int pid = ipc->getCallingPid();
3107 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003108 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003109 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003110 return false;
3111 }
3112 return true;
3113}
3114
Marissa Wall3dad52d2019-03-22 14:03:19 -07003115uint32_t SurfaceFlinger::setClientStateLocked(
3116 const ComposerState& composerState, int64_t desiredPresentTime,
3117 const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
3118 bool privileged) {
chaviwca27f252018-02-06 16:46:39 -08003119 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003120
Vishnu Nairf03652d2019-07-16 17:56:56 -07003121 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003122 if (layer == nullptr) {
Marissa Wall88e20482019-06-24 10:49:42 -07003123 for (auto& listenerCallback : listenerCallbacks) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003124 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Marissa Wall88e20482019-06-24 10:49:42 -07003125 new CallbackHandle(listenerCallback.transactionCompletedListener,
3126 listenerCallback.callbackIds, s.surface));
3127 }
chaviw8b3871a2017-11-01 17:41:01 -07003128 return 0;
3129 }
3130
chaviw8b3871a2017-11-01 17:41:01 -07003131 uint32_t flags = 0;
3132
Garfield Tan8a3083e2018-12-03 13:21:07 -08003133 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003134
3135 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3136 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003137 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003138 layer->pushPendingState();
3139 }
3140
chaviw8b3871a2017-11-01 17:41:01 -07003141 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003142 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003143 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003144 }
chaviw8b3871a2017-11-01 17:41:01 -07003145 }
3146 if (what & layer_state_t::eLayerChanged) {
3147 // NOTE: index needs to be calculated before we update the state
3148 const auto& p = layer->getParent();
3149 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003150 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003151 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003152 mCurrentState.layersSortedByZ.removeAt(idx);
3153 mCurrentState.layersSortedByZ.add(layer);
3154 // we need traversal (state changed)
3155 // AND transaction (list changed)
3156 flags |= eTransactionNeeded|eTraversalNeeded;
3157 }
chaviw8b3871a2017-11-01 17:41:01 -07003158 } else {
3159 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003160 flags |= eTransactionNeeded|eTraversalNeeded;
3161 }
3162 }
chaviw8b3871a2017-11-01 17:41:01 -07003163 }
3164 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003165 // NOTE: index needs to be calculated before we update the state
3166 const auto& p = layer->getParent();
3167 if (p == nullptr) {
3168 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3169 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3170 mCurrentState.layersSortedByZ.removeAt(idx);
3171 mCurrentState.layersSortedByZ.add(layer);
3172 // we need traversal (state changed)
3173 // AND transaction (list changed)
3174 flags |= eTransactionNeeded|eTraversalNeeded;
3175 }
3176 } else {
3177 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3178 flags |= eTransactionNeeded|eTraversalNeeded;
3179 }
chaviw8b3871a2017-11-01 17:41:01 -07003180 }
3181 }
3182 if (what & layer_state_t::eSizeChanged) {
3183 if (layer->setSize(s.w, s.h)) {
3184 flags |= eTraversalNeeded;
3185 }
3186 }
3187 if (what & layer_state_t::eAlphaChanged) {
3188 if (layer->setAlpha(s.alpha))
3189 flags |= eTraversalNeeded;
3190 }
3191 if (what & layer_state_t::eColorChanged) {
3192 if (layer->setColor(s.color))
3193 flags |= eTraversalNeeded;
3194 }
Peiyong Lind3788632018-09-18 16:01:31 -07003195 if (what & layer_state_t::eColorTransformChanged) {
3196 if (layer->setColorTransform(s.colorTransform)) {
3197 flags |= eTraversalNeeded;
3198 }
3199 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003200 if (what & layer_state_t::eBackgroundColorChanged) {
3201 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3202 flags |= eTraversalNeeded;
3203 }
3204 }
chaviw8b3871a2017-11-01 17:41:01 -07003205 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003206 // TODO: b/109894387
3207 //
3208 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3209 // rotation. To see the problem observe that if we have a square parent, and a child
3210 // of the same size, then we rotate the child 45 degrees around it's center, the child
3211 // must now be cropped to a non rectangular 8 sided region.
3212 //
3213 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3214 // private API, and the WindowManager only uses rotation in one case, which is on a top
3215 // level layer in which cropping is not an issue.
3216 //
3217 // However given that abuse of rotation matrices could lead to surfaces extending outside
3218 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3219 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3220 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003221 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003222 flags |= eTraversalNeeded;
3223 }
3224 if (what & layer_state_t::eTransparentRegionChanged) {
3225 if (layer->setTransparentRegionHint(s.transparentRegion))
3226 flags |= eTraversalNeeded;
3227 }
3228 if (what & layer_state_t::eFlagsChanged) {
3229 if (layer->setFlags(s.flags, s.mask))
3230 flags |= eTraversalNeeded;
3231 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003232 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003233 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003234 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003235 if (what & layer_state_t::eCornerRadiusChanged) {
3236 if (layer->setCornerRadius(s.cornerRadius))
3237 flags |= eTraversalNeeded;
3238 }
chaviw8b3871a2017-11-01 17:41:01 -07003239 if (what & layer_state_t::eLayerStackChanged) {
3240 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3241 // We only allow setting layer stacks for top level layers,
3242 // everything else inherits layer stack from its parent.
3243 if (layer->hasParent()) {
3244 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3245 layer->getName().string());
3246 } else if (idx < 0) {
3247 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3248 "that also does not appear in the top level layer list. Something"
3249 " has gone wrong.", layer->getName().string());
3250 } else if (layer->setLayerStack(s.layerStack)) {
3251 mCurrentState.layersSortedByZ.removeAt(idx);
3252 mCurrentState.layersSortedByZ.add(layer);
3253 // we need traversal (state changed)
3254 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003255 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003256 }
3257 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003258 if (what & layer_state_t::eDeferTransaction_legacy) {
3259 if (s.barrierHandle_legacy != nullptr) {
3260 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3261 } else if (s.barrierGbp_legacy != nullptr) {
3262 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003263 if (authenticateSurfaceTextureLocked(gbp)) {
3264 const auto& otherLayer =
3265 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003266 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003267 } else {
3268 ALOGE("Attempt to defer transaction to to an"
3269 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003270 }
3271 }
chaviw8b3871a2017-11-01 17:41:01 -07003272 // We don't trigger a traversal here because if no other state is
3273 // changed, we don't want this to cause any more work
3274 }
chaviw8b3871a2017-11-01 17:41:01 -07003275 if (what & layer_state_t::eReparentChildren) {
3276 if (layer->reparentChildren(s.reparentHandle)) {
3277 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003278 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003279 }
chaviw8b3871a2017-11-01 17:41:01 -07003280 if (what & layer_state_t::eDetachChildren) {
3281 layer->detachChildren();
3282 }
3283 if (what & layer_state_t::eOverrideScalingModeChanged) {
3284 layer->setOverrideScalingMode(s.overrideScalingMode);
3285 // We don't trigger a traversal here because if no other state is
3286 // changed, we don't want this to cause any more work
3287 }
Marissa Wall61c58622018-07-18 10:12:20 -07003288 if (what & layer_state_t::eTransformChanged) {
3289 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3290 }
3291 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3292 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3293 flags |= eTraversalNeeded;
3294 }
3295 if (what & layer_state_t::eCropChanged) {
3296 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3297 }
Marissa Wall861616d2018-10-22 12:52:23 -07003298 if (what & layer_state_t::eFrameChanged) {
3299 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3300 }
Marissa Wall61c58622018-07-18 10:12:20 -07003301 if (what & layer_state_t::eAcquireFenceChanged) {
3302 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3303 }
3304 if (what & layer_state_t::eDataspaceChanged) {
3305 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3306 }
3307 if (what & layer_state_t::eHdrMetadataChanged) {
3308 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3309 }
3310 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3311 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3312 }
3313 if (what & layer_state_t::eApiChanged) {
3314 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3315 }
3316 if (what & layer_state_t::eSidebandStreamChanged) {
3317 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3318 }
Robert Carr720e5062018-07-30 17:45:14 -07003319 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003320 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003321 layer->setInputInfo(s.inputInfo);
3322 flags |= eTraversalNeeded;
3323 } else {
3324 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3325 }
Robert Carr720e5062018-07-30 17:45:14 -07003326 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003327 if (what & layer_state_t::eMetadataChanged) {
3328 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3329 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003330 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3331 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3332 flags |= eTraversalNeeded;
3333 }
3334 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003335 // This has to happen after we reparent children because when we reparent to null we remove
3336 // child layers from current state and remove its relative z. If the children are reparented in
3337 // the same transaction, then we have to make sure we reparent the children first so we do not
3338 // lose its relative z order.
3339 if (what & layer_state_t::eReparent) {
3340 bool hadParent = layer->hasParent();
3341 if (layer->reparent(s.parentHandleForChild)) {
3342 if (!hadParent) {
3343 mCurrentState.layersSortedByZ.remove(layer);
3344 }
3345 flags |= eTransactionNeeded | eTraversalNeeded;
3346 }
3347 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003348 std::vector<sp<CallbackHandle>> callbackHandles;
Marissa Wall3dad52d2019-03-22 14:03:19 -07003349 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!listenerCallbacks.empty())) {
Marissa Wall3dad52d2019-03-22 14:03:19 -07003350 for (const auto& [listener, callbackIds] : listenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003351 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3352 }
3353 }
Marissa Wall78b72202019-03-15 14:58:34 -07003354 bool bufferChanged = what & layer_state_t::eBufferChanged;
3355 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3356 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003357 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003358 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003359 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3360 if (success) {
3361 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3362 success = ClientCache::getInstance()
3363 .registerErasedRecipient(s.cachedBuffer,
3364 wp<ClientCache::ErasedRecipient>(this));
3365 if (!success) {
3366 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3367 }
3368 }
Marissa Wall78b72202019-03-15 14:58:34 -07003369 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003370 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003371 } else if (bufferChanged) {
3372 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003373 }
Marissa Wall78b72202019-03-15 14:58:34 -07003374 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003375 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003376 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003377 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003378 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003379 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3380 // Do not put anything that updates layer state or modifies flags after
3381 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003382 return flags;
3383}
3384
chaviw273171b2018-12-26 11:46:30 -08003385uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3386 uint32_t flags = 0;
3387 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3388 flags |= eTraversalNeeded;
3389 }
3390
chaviwa911b102019-02-14 10:18:33 -08003391 if (inputWindowCommands.syncInputWindows) {
3392 flags |= eTraversalNeeded;
3393 }
3394
Vishnu Nairec0ab382019-02-13 15:32:56 -08003395 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003396 return flags;
3397}
3398
Marissa Wall2d814fb2019-04-09 18:52:57 +00003399status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3400 uint32_t h, PixelFormat format, uint32_t flags,
3401 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003402 sp<IGraphicBufferProducer>* gbp,
3403 const sp<IBinder>& parentHandle,
3404 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003405 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003406 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003407 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003408 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003409 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003410
Robert Carrc0df3122019-04-11 13:18:21 -07003411 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3412 "Expected only one of parentLayer or parentHandle to be non-null. "
3413 "Programmer error?");
3414
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003415 status_t result = NO_ERROR;
3416
3417 sp<Layer> layer;
3418
Cody Northropbc755282017-03-31 12:00:08 -06003419 String8 uniqueName = getUniqueLayerName(name);
3420
Evan Roskya1f1e152019-01-24 16:17:46 -08003421 bool primaryDisplayOnly = false;
3422
3423 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3424 // TODO b/64227542
3425 if (metadata.has(METADATA_WINDOW_TYPE)) {
3426 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3427 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003428 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003429 primaryDisplayOnly = true;
3430 }
3431 }
3432
Mathias Agopian3165cc22012-08-08 19:42:09 -07003433 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003434 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003435 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3436 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003437
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003438 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003439 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003440 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3441 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003442 break;
chaviw13fdc492017-06-27 12:40:18 -07003443 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003444 // check if buffer size is set for color layer.
3445 if (w > 0 || h > 0) {
3446 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3447 int(w), int(h));
3448 return BAD_VALUE;
3449 }
3450
Evan Roskya1f1e152019-01-24 16:17:46 -08003451 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3452 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003453 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003454 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003455 // check if buffer size is set for container layer.
3456 if (w > 0 || h > 0) {
3457 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3458 int(w), int(h));
3459 return BAD_VALUE;
3460 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003461 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3462 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003463 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003464 default:
3465 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003466 break;
3467 }
3468
Dan Stoza7d89d062015-04-30 13:29:25 -07003469 if (result != NO_ERROR) {
3470 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003471 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003472
Evan Roskya1f1e152019-01-24 16:17:46 -08003473 if (primaryDisplayOnly) {
3474 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003475 }
3476
Robert Carrb89ea9d2018-12-10 13:01:14 -08003477 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003478 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3479 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003480 if (result != NO_ERROR) {
3481 return result;
3482 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003483 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003484
3485 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003486 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003487}
3488
Cody Northropbc755282017-03-31 12:00:08 -06003489String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3490{
3491 bool matchFound = true;
3492 uint32_t dupeCounter = 0;
3493
3494 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3495 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3496
Dan Stoza436ccf32018-06-21 12:10:12 -07003497 // Grab the state lock since we're accessing mCurrentState
3498 Mutex::Autolock lock(mStateLock);
3499
Cody Northropbc755282017-03-31 12:00:08 -06003500 // Loop over layers until we're sure there is no matching name
3501 while (matchFound) {
3502 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003503 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003504 if (layer->getName() == uniqueName) {
3505 matchFound = true;
3506 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3507 }
3508 });
3509 }
3510
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003511 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3512 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003513
3514 return uniqueName;
3515}
3516
Marissa Wallfd668622018-05-10 10:21:13 -07003517status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3518 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003519 LayerMetadata metadata, PixelFormat& format,
3520 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003521 sp<IGraphicBufferProducer>* gbp,
3522 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003524 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003525 case PIXEL_FORMAT_TRANSPARENT:
3526 case PIXEL_FORMAT_TRANSLUCENT:
3527 format = PIXEL_FORMAT_RGBA_8888;
3528 break;
3529 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003530 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003531 break;
3532 }
3533
Evan Roskya1f1e152019-01-24 16:17:46 -08003534 sp<BufferQueueLayer> layer = getFactory().createBufferQueueLayer(
3535 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wallfd668622018-05-10 10:21:13 -07003536 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003537 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003538 *handle = layer->getHandle();
3539 *gbp = layer->getProducer();
3540 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003541 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003542
Marissa Wallfd668622018-05-10 10:21:13 -07003543 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003544 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003545}
3546
Marissa Wall61c58622018-07-18 10:12:20 -07003547status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3548 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003549 LayerMetadata metadata, sp<IBinder>* handle,
3550 sp<Layer>* outLayer) {
3551 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(
3552 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Marissa Wall61c58622018-07-18 10:12:20 -07003553 *handle = layer->getHandle();
3554 *outLayer = layer;
3555
3556 return NO_ERROR;
3557}
3558
Evan Roskya1f1e152019-01-24 16:17:46 -08003559status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
3560 uint32_t h, uint32_t flags, LayerMetadata metadata,
3561 sp<IBinder>* handle, sp<Layer>* outLayer) {
3562 *outLayer = getFactory().createColorLayer(
3563 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003564 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003565 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003566}
3567
Evan Roskya1f1e152019-01-24 16:17:46 -08003568status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
3569 uint32_t w, uint32_t h, uint32_t flags,
3570 LayerMetadata metadata, sp<IBinder>* handle,
3571 sp<Layer>* outLayer) {
3572 *outLayer = getFactory().createContainerLayer(
3573 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003574 *handle = (*outLayer)->getHandle();
3575 return NO_ERROR;
3576}
3577
3578
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003579void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003580 mLayersPendingRemoval.add(layer);
3581 mLayersRemoved = true;
3582 setTransactionFlags(eTransactionNeeded);
3583}
3584
Robert Carr695d5282018-12-18 15:27:58 -08003585void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003586{
Robert Carr2e102c92018-10-23 12:11:15 -07003587 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003588 // If a layer has a parent, we allow it to out-live it's handle
3589 // with the idea that the parent holds a reference and will eventually
3590 // be cleaned up. However no one cleans up the top-level so we do so
3591 // here.
3592 if (layer->getParent() == nullptr) {
3593 mCurrentState.layersSortedByZ.remove(layer);
3594 }
3595 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003596
3597 auto it = mLayersByLocalBinderToken.begin();
3598 while (it != mLayersByLocalBinderToken.end()) {
3599 if (it->second == layer) {
3600 it = mLayersByLocalBinderToken.erase(it);
3601 } else {
3602 it++;
3603 }
3604 }
3605
Robert Carr695d5282018-12-18 15:27:58 -08003606 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003607}
3608
Mathias Agopianb60314a2012-04-10 22:09:54 -07003609// ---------------------------------------------------------------------------
3610
Andy McFadden13a082e2012-08-24 10:16:42 -07003611void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003612 const auto display = getDefaultDisplayDeviceLocked();
3613 if (!display) return;
3614
3615 const sp<IBinder> token = display->getDisplayToken().promote();
3616 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003617
Jesse Hall01e29052013-02-19 16:13:35 -08003618 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003619 Vector<ComposerState> state;
3620 Vector<DisplayState> displays;
3621 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003622 d.what = DisplayState::eDisplayProjectionChanged |
3623 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003624 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003625 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003626 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003627 d.frame.makeInvalid();
3628 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003629 d.width = 0;
3630 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003631 displays.add(d);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003632 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003633
Dominik Laskowskie9774092018-12-11 10:04:24 -08003634 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003635
Dominik Laskowski83b88212018-12-11 13:34:06 -08003636 const nsecs_t vsyncPeriod = getVsyncPeriod();
3637 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003638
Brian Andersond0010582017-03-07 13:20:31 -08003639 // Use phase of 0 since phase is not known.
3640 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003641 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003642 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003643}
3644
3645void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003646 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003647 postMessageAsync(
3648 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003649}
3650
Ady Abraham27c70212019-06-11 10:52:26 -07003651void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3652 if (mHWCVsyncState != enabled) {
3653 getHwComposer().setVsyncEnabled(displayId, enabled);
3654 mHWCVsyncState = enabled;
3655 }
3656}
3657
Dominik Laskowskie9774092018-12-11 10:04:24 -08003658void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003659 if (display->isVirtual()) {
3660 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003661 return;
3662 }
3663
Dominik Laskowski075d3172018-05-24 15:50:06 -07003664 const auto displayId = display->getId();
3665 LOG_ALWAYS_FATAL_IF(!displayId);
3666
Dominik Laskowski34157762018-10-31 13:07:19 -07003667 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003668
3669 int currentMode = display->getPowerMode();
3670 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003671 return;
3672 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003673
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003674 display->setPowerMode(mode);
3675
Lloyd Pique4dccc412018-01-22 17:21:36 -08003676 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003677 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003678 }
3679
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003680 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003681 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003682 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003683 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003684 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003685 mScheduler->onScreenAcquired(mAppConnectionHandle);
3686 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003688
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003689 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003690 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003691 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003692
3693 struct sched_param param = {0};
3694 param.sched_priority = 1;
3695 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3696 ALOGW("Couldn't set SCHED_FIFO on display on");
3697 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003698 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003699 // Turn off the display
3700 struct sched_param param = {0};
3701 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3702 ALOGW("Couldn't set SCHED_OTHER on display off");
3703 }
3704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003705 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003706 mScheduler->disableHardwareVsync(true);
3707 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003708 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003709
Ady Abraham27c70212019-06-11 10:52:26 -07003710 // Make sure HWVsync is disabled before turning off the display
3711 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3712
Dominik Laskowski075d3172018-05-24 15:50:06 -07003713 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003714 mVisibleRegionsDirty = true;
3715 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003716 } else if (mode == HWC_POWER_MODE_DOZE ||
3717 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003718 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003719 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003721 mScheduler->onScreenAcquired(mAppConnectionHandle);
3722 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003723 }
3724 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3725 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003726 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003727 mScheduler->disableHardwareVsync(true);
3728 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003729 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003730 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003731 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003732 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003733 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003734 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003735
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003736 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003737 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003738 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003739 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003740 }
3741
Dominik Laskowski34157762018-10-31 13:07:19 -07003742 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003743}
3744
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003745void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003746 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003747 const auto display = getDisplayDevice(displayToken);
3748 if (!display) {
3749 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3750 displayToken.get());
3751 } else if (display->isVirtual()) {
3752 ALOGW("Attempt to set power mode %d for virtual display", mode);
3753 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003754 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003755 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003756 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003757}
3758
3759// ---------------------------------------------------------------------------
3760
Dominik Laskowskic2867142019-01-21 11:33:38 -08003761status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3762 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003763 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003764
Mathias Agopianbd115332013-04-18 16:41:04 -07003765 IPCThreadState* ipc = IPCThreadState::self();
3766 const int pid = ipc->getCallingPid();
3767 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003768
Mathias Agopianbd115332013-04-18 16:41:04 -07003769 if ((uid != AID_SHELL) &&
3770 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003771 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3772 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003773 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003774 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003775 // (this would indicate SF is stuck, but we want to be able to
3776 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003777 status_t err = mStateLock.timedLock(s2ns(1));
3778 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003779 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003780 StringAppendF(&result,
3781 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3782 "(no locks held)\n",
3783 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003784 }
3785
Dominik Laskowskic2867142019-01-21 11:33:38 -08003786 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07003787
Dominik Laskowskic2867142019-01-21 11:33:38 -08003788 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003789 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003790 {"--dispsync"s,
3791 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003792 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003793 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3794 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3795 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3796 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3797 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3798 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003799 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003800 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3801 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003802
Dominik Laskowskic2867142019-01-21 11:33:38 -08003803 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003804
Dominik Laskowski46470112019-08-02 13:13:11 -07003805 const auto it = dumpers.find(flag);
3806 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003807 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003808 } else if (!asProto) {
3809 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003810 }
3811
Mathias Agopian9795c422009-08-26 16:36:26 -07003812 if (locked) {
3813 mStateLock.unlock();
3814 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003815
Dominik Laskowski46470112019-08-02 13:13:11 -07003816 if (it == dumpers.end()) {
3817 const LayersProto layersProto = dumpProtoFromMainThread();
3818 if (asProto) {
3819 result.append(layersProto.SerializeAsString());
3820 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003821 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003822 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3823 result.append(LayerProtoParser::layerTreeToString(layerTree));
3824 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003825 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003826 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003827 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003829 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003830 return NO_ERROR;
3831}
3832
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003833status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3834 if (asProto && mTracing.isEnabled()) {
3835 mTracing.writeToFileAsync();
3836 }
3837
3838 return doDump(fd, DumpArgs(), asProto);
3839}
3840
Dominik Laskowskic2867142019-01-21 11:33:38 -08003841void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003842 mCurrentState.traverseInZOrder(
3843 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003844}
3845
Dominik Laskowskic2867142019-01-21 11:33:38 -08003846void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003847 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003848
Dominik Laskowskic2867142019-01-21 11:33:38 -08003849 if (args.size() > 1) {
3850 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003851 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003852 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003853 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003854 }
Robert Carr2047fae2016-11-28 14:09:09 -08003855 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003856 } else {
3857 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003858 }
3859}
3860
Dominik Laskowskic2867142019-01-21 11:33:38 -08003861void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08003862 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003863 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003864 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003865 }
Robert Carr2047fae2016-11-28 14:09:09 -08003866 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003867
Svetoslavd85084b2014-03-20 10:28:31 -07003868 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003869}
3870
Dominik Laskowskic2867142019-01-21 11:33:38 -08003871void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3872 mTimeStats->parseArgs(asProto, args, result);
3873}
3874
Jamie Gennis6547ff42013-07-16 20:12:42 -07003875// This should only be called from the main thread. Otherwise it would need
3876// the lock and should use mCurrentState rather than mDrawingState.
3877void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003878 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003879 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003880 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003881
3882 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3883}
3884
Yiwei Zhang5434a782018-12-05 18:06:32 -08003885void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003886 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003887
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003888 if (isLayerTripleBufferingDisabled())
3889 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003890
Yiwei Zhang5434a782018-12-05 18:06:32 -08003891 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3892 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3893 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3894 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3895 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3896 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003897 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003898}
3899
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003900void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003901 mScheduler->dump(result);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003902 StringAppendF(&result, "+ Refresh rate switching: %s\n",
3903 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowski98041832019-08-01 18:35:59 -07003904 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
3905
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003906 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003907 result.append("\n");
3908
Ana Krulec757f63a2019-01-25 10:46:18 -08003909 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003910 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003911 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003912 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003913
Ady Abraham42b3beb2019-07-09 18:09:52 -07003914 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003915 for (int32_t configId : mAllowedDisplayConfigs) {
3916 StringAppendF(&result, "%" PRIu32 " Hz, ",
3917 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003918 }
3919 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3920 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003921
Ana Krulecc2870422019-01-29 19:00:58 -08003922 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003923}
3924
Yiwei Zhang5434a782018-12-05 18:06:32 -08003925void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3926 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003927 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3928 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003929 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003930 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003931 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003932 }
David Sodman4a36e932017-11-07 14:29:47 -08003933 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003934 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003935 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003936 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3937 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003938}
3939
Dan Stozae77c7662016-05-13 11:37:28 -07003940void SurfaceFlinger::recordBufferingStats(const char* layerName,
3941 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003942 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3943 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003944 for (const auto& segment : history) {
3945 if (!segment.usedThirdBuffer) {
3946 stats.twoBufferTime += segment.totalTime;
3947 }
3948 if (segment.occupancyAverage < 1.0f) {
3949 stats.doubleBufferedTime += segment.totalTime;
3950 } else if (segment.occupancyAverage < 2.0f) {
3951 stats.tripleBufferedTime += segment.totalTime;
3952 }
3953 ++stats.numSegments;
3954 stats.totalTime += segment.totalTime;
3955 }
3956}
3957
Yiwei Zhang5434a782018-12-05 18:06:32 -08003958void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
3959 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07003960
3961 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3962 const size_t count = currentLayers.size();
3963 for (size_t i=0 ; i<count ; i++) {
3964 currentLayers[i]->dumpFrameEvents(result);
3965 }
3966}
3967
Yiwei Zhang5434a782018-12-05 18:06:32 -08003968void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07003969 result.append("Buffering stats:\n");
3970 result.append(" [Layer name] <Active time> <Two buffer> "
3971 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003972 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003973 typedef std::tuple<std::string, float, float, float> BufferTuple;
3974 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003975 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003976 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003977 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003978 if (stats.numSegments == 0) {
3979 continue;
3980 }
3981 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3982 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3983 stats.totalTime;
3984 float doubleBufferRatio = static_cast<float>(
3985 stats.doubleBufferedTime) / stats.totalTime;
3986 float tripleBufferRatio = static_cast<float>(
3987 stats.tripleBufferedTime) / stats.totalTime;
3988 sorted.insert({activeTime, {name, twoBufferRatio,
3989 doubleBufferRatio, tripleBufferRatio}});
3990 }
3991 for (const auto& sortedPair : sorted) {
3992 float activeTime = sortedPair.first;
3993 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003994 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
3995 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07003996 }
3997 result.append("\n");
3998}
3999
Yiwei Zhang5434a782018-12-05 18:06:32 -08004000void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004001 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004002 const auto displayId = display->getId();
4003 if (!displayId) {
4004 continue;
4005 }
4006 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004007 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004008 continue;
4009 }
4010
Yiwei Zhang5434a782018-12-05 18:06:32 -08004011 StringAppendF(&result,
4012 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4013 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004014 uint8_t port;
4015 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004016 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004017 result.append("no identification data\n");
4018 continue;
4019 }
4020
4021 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004022 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004023 continue;
4024 }
4025
4026 const auto edid = parseEdid(data);
4027 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004028 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004029 continue;
4030 }
4031
Yiwei Zhang5434a782018-12-05 18:06:32 -08004032 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004033 result.append(edid->displayName.data(), edid->displayName.length());
4034 result.append("\"\n");
4035 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004036}
4037
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004038void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4039 std::string& result) const {
4040 hwc2_display_t hwcDisplayId;
4041 uint8_t port;
4042 DisplayIdentificationData data;
4043
4044 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4045 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4046 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4047 }
4048}
4049
Yiwei Zhang5434a782018-12-05 18:06:32 -08004050void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004051 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004052 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4053 StringAppendF(&result, "DisplayColorSetting: %s\n",
4054 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004055
4056 // TODO: print out if wide-color mode is active or not
4057
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004058 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004059 const auto displayId = display->getId();
4060 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004061 continue;
4062 }
4063
Yiwei Zhang5434a782018-12-05 18:06:32 -08004064 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004065 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004066 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004067 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004068 }
4069
Lloyd Pique32cbe282018-10-19 13:09:22 -07004070 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004071 StringAppendF(&result, " Current color mode: %s (%d)\n",
4072 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004073 }
4074 result.append("\n");
4075}
4076
Vishnu Nair8406fd72019-07-30 11:29:31 -07004077LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004078 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004079 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004080 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004081 layer->writeToProtoDrawingState(layerProto, traceFlags);
4082 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004083 });
4084
4085 return layersProto;
4086}
4087
Vishnu Nair0f085c62019-08-30 08:49:12 -07004088void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4089 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4090 // it.
4091 LayerProto* rootProto = layersProto.add_layers();
4092 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4093 rootProto->set_id(offscreenRootLayerId);
4094 rootProto->set_name("Offscreen Root");
4095
4096 for (Layer* offscreenLayer : mOffscreenLayers) {
4097 // Add layer as child of the fake root
4098 rootProto->add_children(offscreenLayer->sequence);
4099
4100 // Add layer
4101 LayerProto* layerProto = layersProto.add_layers();
4102 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4103 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4104 traceFlags);
4105 layerProto->set_parent(offscreenRootLayerId);
4106
4107 // Add children
4108 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4109 if (layer == offscreenLayer) {
4110 return;
4111 }
4112 LayerProto* childProto = layersProto.add_layers();
4113 layer->writeToProtoDrawingState(childProto, traceFlags);
4114 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4115 });
4116 }
4117}
4118
Vishnu Nair8406fd72019-07-30 11:29:31 -07004119LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4120 LayersProto layersProto;
4121 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4122 return layersProto;
4123}
4124
Vishnu Nair0f085c62019-08-30 08:49:12 -07004125void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4126 result.append("Offscreen Layers:\n");
4127 postMessageSync(new LambdaMessage([&]() {
4128 for (Layer* offscreenLayer : mOffscreenLayers) {
4129 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4130 layer->dumpCallingUidPid(result);
4131 });
4132 }
4133 }));
4134}
4135
Dominik Laskowskic2867142019-01-21 11:33:38 -08004136void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4137 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004138 Colorizer colorizer(colorize);
4139
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004140 // figure out if we're stuck somewhere
4141 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004142 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004143 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4144
4145 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004146 * Dump library configuration.
4147 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004148
4149 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004150 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004151 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004152 appendSfConfigString(result);
4153 appendUiConfigString(result);
4154 appendGuiConfigString(result);
4155 result.append("\n");
4156
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004157 result.append("\nDisplay identification data:\n");
4158 dumpDisplayIdentificationData(result);
4159
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004160 result.append("\nWide-Color information:\n");
4161 dumpWideColorInfo(result);
4162
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004163 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004164 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004165 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004166 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004167 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004168
Andy McFadden41d67d72014-04-25 16:58:34 -07004169 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004170 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004171 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004172 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004173 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004174
Dan Stozab90cf072015-03-05 11:05:59 -08004175 dumpStaticScreenStats(result);
4176 result.append("\n");
4177
Alec Mouri40189b02019-03-05 15:07:54 -08004178 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4179 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4180 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004181
Dan Stozae77c7662016-05-13 11:37:28 -07004182 dumpBufferingStats(result);
4183
Andy McFadden4803b742012-09-24 19:07:20 -07004184 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004185 * Dump the visible layer list
4186 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004187 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004188 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004189 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4190 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004191 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004192
Chia-I Wu2f884132018-09-13 15:17:58 -07004193 {
Lloyd Pique207def92019-02-28 16:09:52 -08004194 StringAppendF(&result, "Composition layers\n");
4195 mDrawingState.traverseInZOrder([&](Layer* layer) {
4196 auto compositionLayer = layer->getCompositionLayer();
4197 if (compositionLayer) compositionLayer->dump(result);
4198 });
4199 }
4200
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004202 * Dump Display state
4203 */
4204
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004205 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004206 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004207 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004208 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004209 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004210 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004211 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004212
4213 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004214 * Dump SurfaceFlinger global state
4215 */
4216
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004217 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004218 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004220
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004221 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004222
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004223 DebugEGLImageTracker::getInstance()->dump(result);
4224
Dominik Laskowski075d3172018-05-24 15:50:06 -07004225 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004226 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4227 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004228 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4229 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004230 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004231 StringAppendF(&result,
4232 " transaction-flags : %08x\n"
4233 " gpu_to_cpu_unsupported : %d\n",
4234 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004235
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004236 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004237 displayId && getHwComposer().isConnected(*displayId)) {
4238 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004239 StringAppendF(&result,
4240 " refresh-rate : %f fps\n"
4241 " x-dpi : %f\n"
4242 " y-dpi : %f\n",
4243 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4244 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004245 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246
Yiwei Zhang5434a782018-12-05 18:06:32 -08004247 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004248
Dan Stozae22aec72016-08-01 13:20:59 -07004249 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004250 * Tracing state
4251 */
4252 mTracing.dump(result);
4253 result.append("\n");
4254
4255 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004256 * HWC layer minidump
4257 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004258 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004259 const auto displayId = display->getId();
4260 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004261 continue;
4262 }
4263
Yiwei Zhang5434a782018-12-05 18:06:32 -08004264 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004265 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004266 const sp<DisplayDevice> displayDevice = display;
4267 mCurrentState.traverseInZOrder(
4268 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004269 result.append("\n");
4270 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004271
4272 /*
4273 * Dump HWComposer state
4274 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004275 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004276 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004277 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004278 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004279 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004280 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004281
4282 /*
4283 * Dump gralloc state
4284 */
4285 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4286 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004287
4288 /*
4289 * Dump VrFlinger state if in use.
4290 */
4291 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4292 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004293 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004294 result.append("\n");
4295 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004296
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004297 result.append(mTimeStats->miniDump());
4298 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299}
4300
Chia-I Wu28f320b2018-05-03 11:02:56 -07004301void SurfaceFlinger::updateColorMatrixLocked() {
4302 mat4 colorMatrix;
4303 if (mGlobalSaturationFactor != 1.0f) {
4304 // Rec.709 luma coefficients
4305 float3 luminance{0.213f, 0.715f, 0.072f};
4306 luminance *= 1.0f - mGlobalSaturationFactor;
4307 mat4 saturationMatrix = mat4(
4308 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4309 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4310 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4311 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4312 );
4313 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4314 } else {
4315 colorMatrix = mClientColorMatrix * mDaltonizer();
4316 }
4317
4318 if (mCurrentState.colorMatrix != colorMatrix) {
4319 mCurrentState.colorMatrix = colorMatrix;
4320 mCurrentState.colorMatrixChanged = true;
4321 setTransactionFlags(eTransactionNeeded);
4322 }
4323}
4324
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004325status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004326#pragma clang diagnostic push
4327#pragma clang diagnostic error "-Wswitch-enum"
4328 switch (static_cast<ISurfaceComposerTag>(code)) {
4329 // These methods should at minimum make sure that the client requested
4330 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004331 case BOOT_FINISHED:
4332 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004333 case CREATE_DISPLAY:
4334 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004335 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004336 case GET_ANIMATION_FRAME_STATS:
4337 case GET_HDR_CAPABILITIES:
4338 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004339 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004340 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004341 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004342 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004343 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004344 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004345 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004346 case GET_DISPLAYED_CONTENT_SAMPLE:
4347 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004348 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4349 IPCThreadState* ipc = IPCThreadState::self();
4350 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4351 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004352 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004353 }
Robert Carr1db73f62016-12-21 12:58:51 -08004354 return OK;
4355 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004356 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004357 IPCThreadState* ipc = IPCThreadState::self();
4358 const int pid = ipc->getCallingPid();
4359 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004360 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4361 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004362 return PERMISSION_DENIED;
4363 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004364 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004365 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004366 // Used by apps to hook Choreographer to SurfaceFlinger.
4367 case CREATE_DISPLAY_EVENT_CONNECTION:
4368 // The following calls are currently used by clients that do not
4369 // request necessary permissions. However, they do not expose any secret
4370 // information, so it is OK to pass them.
4371 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004372 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004373 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004374 case GET_PHYSICAL_DISPLAY_IDS:
4375 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004376 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004377 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004378 case GET_DISPLAY_CONFIGS:
4379 case GET_DISPLAY_STATS:
4380 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4381 // Calling setTransactionState is safe, because you need to have been
4382 // granted a reference to Client* and Handle* to do anything with it.
4383 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004384 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004385 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004386 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004387 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004388 case IS_WIDE_COLOR_DISPLAY:
4389 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4390 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004391 return OK;
4392 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004393 case CAPTURE_LAYERS: {
4394 IPCThreadState* ipc = IPCThreadState::self();
4395 const int pid = ipc->getCallingPid();
4396 const int uid = ipc->getCallingUid();
4397 // allow media to capture layer for video thumbnails
4398 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4399 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4400 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4401 return PERMISSION_DENIED;
4402 }
4403 return OK;
4404 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004405 case CAPTURE_SCREEN:
4406 case ADD_REGION_SAMPLING_LISTENER:
4407 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004408 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004409 IPCThreadState* ipc = IPCThreadState::self();
4410 const int pid = ipc->getCallingPid();
4411 const int uid = ipc->getCallingUid();
4412 if ((uid != AID_GRAPHICS) &&
4413 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4414 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4415 return PERMISSION_DENIED;
4416 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004417 return OK;
4418 }
4419 // The following codes are deprecated and should never be allowed to access SF.
4420 case CONNECT_DISPLAY_UNUSED:
4421 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4422 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4423 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004424 }
chaviw93df2ea2019-04-30 16:45:12 -07004425 case CAPTURE_SCREEN_BY_ID: {
4426 IPCThreadState* ipc = IPCThreadState::self();
4427 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004428 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004429 return OK;
4430 }
4431 return PERMISSION_DENIED;
4432 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004433 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004434
4435 // These codes are used for the IBinder protocol to either interrogate the recipient
4436 // side of the transaction for its canonical interface descriptor or to dump its state.
4437 // We let them pass by default.
4438 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4439 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4440 code == IBinder::SYSPROPS_TRANSACTION) {
4441 return OK;
4442 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004443 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004444 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004445 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004446 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4447 return OK;
4448 }
4449 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4450 return PERMISSION_DENIED;
4451#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004452}
4453
Ana Krulec13be8ad2018-08-21 02:43:56 +00004454status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4455 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004456 status_t credentialCheck = CheckTransactCodeCredentials(code);
4457 if (credentialCheck != OK) {
4458 return credentialCheck;
4459 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004460
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004461 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4462 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004463 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004464 IPCThreadState* ipc = IPCThreadState::self();
4465 const int uid = ipc->getCallingUid();
4466 if (CC_UNLIKELY(uid != AID_SYSTEM
4467 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004468 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004469 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004470 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004471 return PERMISSION_DENIED;
4472 }
4473 int n;
4474 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004475 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004476 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 return NO_ERROR;
4478 case 1002: // SHOW_UPDATES
4479 n = data.readInt32();
4480 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004481 invalidateHwcGeometry();
4482 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004483 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004485 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004486 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004487 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004488 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004489 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004490 setTransactionFlags(
4491 eTransactionNeeded|
4492 eDisplayTransactionNeeded|
4493 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004494 return NO_ERROR;
4495 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004496 case 1006:{ // send empty update
4497 signalRefresh();
4498 return NO_ERROR;
4499 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004500 case 1008: // toggle use of hw composer
4501 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004502 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004503 invalidateHwcGeometry();
4504 repaintEverything();
4505 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004506 case 1009: // toggle use of transform hint
4507 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004508 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004509 invalidateHwcGeometry();
4510 repaintEverything();
4511 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004512 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004513 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004514 reply->writeInt32(0);
4515 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004516 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004517 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004518 return NO_ERROR;
4519 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004520 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004521 if (!display) {
4522 return NAME_NOT_FOUND;
4523 }
4524
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004525 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004526 return NO_ERROR;
4527 }
4528 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004529 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004530 // daltonize
4531 n = data.readInt32();
4532 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004533 case 1:
4534 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4535 break;
4536 case 2:
4537 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4538 break;
4539 case 3:
4540 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4541 break;
4542 default:
4543 mDaltonizer.setType(ColorBlindnessType::None);
4544 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004545 }
4546 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004547 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004548 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004549 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004550 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004551
4552 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004553 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004554 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004555 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004556 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004557 // apply a color matrix
4558 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004559 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004560 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004561 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004562 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004563 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004564 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004565 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004566 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004567 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004568 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004569
4570 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4571 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004572 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004573 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4574 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4575 }
4576
Chia-I Wu28f320b2018-05-03 11:02:56 -07004577 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004578 return NO_ERROR;
4579 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004580 case 1016: { // Unused.
4581 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004582 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004583 case 1017: {
4584 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004585 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004586 return NO_ERROR;
4587 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004588 case 1018: { // Modify Choreographer's phase offset
4589 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004590 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004591 return NO_ERROR;
4592 }
4593 case 1019: { // Modify SurfaceFlinger's phase offset
4594 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004595 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004596 return NO_ERROR;
4597 }
Irvel468051e2016-06-13 16:44:44 -07004598 case 1020: { // Layer updates interceptor
4599 n = data.readInt32();
4600 if (n) {
4601 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004602 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004603 }
4604 else{
4605 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004606 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004607 }
4608 return NO_ERROR;
4609 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004610 case 1021: { // Disable HWC virtual displays
4611 n = data.readInt32();
4612 mUseHwcVirtualDisplays = !n;
4613 return NO_ERROR;
4614 }
Romain Guy0147a172017-06-01 13:53:56 -07004615 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004616 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004617 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004618
Chia-I Wu28f320b2018-05-03 11:02:56 -07004619 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004620 return NO_ERROR;
4621 }
Romain Guy54f154a2017-10-24 21:40:32 +01004622 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004623 int32_t colorMode;
4624
Chia-I Wu0d711262018-05-21 15:19:35 -07004625 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004626 if (data.readInt32(&colorMode) == NO_ERROR) {
4627 mForceColorMode = static_cast<ColorMode>(colorMode);
4628 }
Romain Guy54f154a2017-10-24 21:40:32 +01004629 invalidateHwcGeometry();
4630 repaintEverything();
4631 return NO_ERROR;
4632 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004633 // Deprecate, use 1030 to check whether the device is color managed.
4634 case 1024: {
4635 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004636 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004637 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004638 n = data.readInt32();
4639 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004640 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004641 Mutex::Autolock lock(mStateLock);
4642 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004643 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004644 reply->writeInt32(NO_ERROR);
4645 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004646 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004647 bool writeFile = false;
4648 {
4649 Mutex::Autolock lock(mStateLock);
4650 mTracingEnabledChanged = true;
4651 writeFile = mTracing.disable();
4652 }
4653
4654 if (writeFile) {
4655 reply->writeInt32(mTracing.writeToFile());
4656 } else {
4657 reply->writeInt32(NO_ERROR);
4658 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004659 }
4660 return NO_ERROR;
4661 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004662 case 1026: { // Get layer tracing status
4663 reply->writeBool(mTracing.isEnabled());
4664 return NO_ERROR;
4665 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004666 // Is a DisplayColorSetting supported?
4667 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004668 const auto display = getDefaultDisplayDevice();
4669 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004670 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004671 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004672
4673 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4674 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004675 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004676 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004677 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004678 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004679 reply->writeBool(true);
4680 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004681 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004682 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004683 break;
4684 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004685 reply->writeBool(
4686 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004687 break;
4688 }
4689 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004690 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004691 // Is VrFlinger active?
4692 case 1028: {
4693 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004694 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004695 return NO_ERROR;
4696 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004697 // Set buffer size for SF tracing (value in KB)
4698 case 1029: {
4699 n = data.readInt32();
4700 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4701 ALOGW("Invalid buffer size: %d KB", n);
4702 reply->writeInt32(BAD_VALUE);
4703 return BAD_VALUE;
4704 }
4705
4706 ALOGD("Updating trace buffer to %d KB", n);
4707 mTracing.setBufferSize(n * 1024);
4708 reply->writeInt32(NO_ERROR);
4709 return NO_ERROR;
4710 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004711 // Is device color managed?
4712 case 1030: {
4713 reply->writeBool(useColorManagement);
4714 return NO_ERROR;
4715 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004716 // Override default composition data space
4717 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4718 // && adb shell stop zygote && adb shell start zygote
4719 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4720 // adb shell stop zygote && adb shell start zygote
4721 case 1031: {
4722 Mutex::Autolock _l(mStateLock);
4723 n = data.readInt32();
4724 if (n) {
4725 n = data.readInt32();
4726 if (n) {
4727 Dataspace dataspace = static_cast<Dataspace>(n);
4728 if (!validateCompositionDataspace(dataspace)) {
4729 return BAD_VALUE;
4730 }
4731 mDefaultCompositionDataspace = dataspace;
4732 }
4733 n = data.readInt32();
4734 if (n) {
4735 Dataspace dataspace = static_cast<Dataspace>(n);
4736 if (!validateCompositionDataspace(dataspace)) {
4737 return BAD_VALUE;
4738 }
4739 mWideColorGamutCompositionDataspace = dataspace;
4740 }
4741 } else {
4742 // restore composition data space.
4743 mDefaultCompositionDataspace = defaultCompositionDataspace;
4744 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4745 }
4746 return NO_ERROR;
4747 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004748 // Set trace flags
4749 case 1033: {
4750 n = data.readUint32();
4751 ALOGD("Updating trace flags to 0x%x", n);
4752 mTracing.setTraceFlags(n);
4753 reply->writeInt32(NO_ERROR);
4754 return NO_ERROR;
4755 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004756 case 1034: {
4757 // TODO(b/129297325): expose this via developer menu option
4758 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004759 if (n && !mRefreshRateOverlay &&
4760 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004761 RefreshRateType type;
4762 {
4763 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4764 type = mDesiredActiveConfig.type;
4765 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004766 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004767 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004768 } else if (!n) {
4769 mRefreshRateOverlay.reset();
4770 }
4771 return NO_ERROR;
4772 }
Ady Abraham34392f72019-04-10 11:29:27 -07004773 case 1035: {
4774 n = data.readInt32();
4775 mDebugDisplayConfigSetByBackdoor = false;
4776 if (n >= 0) {
4777 const auto displayToken = getInternalDisplayToken();
4778 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4779 if (result != NO_ERROR) {
4780 return result;
4781 }
4782 mDebugDisplayConfigSetByBackdoor = true;
4783 }
4784 return NO_ERROR;
4785 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004786 }
4787 }
4788 return err;
4789}
4790
Steven Thomas6d8110b2017-08-31 18:24:21 -07004791void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004792 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004793 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004794}
4795
Ana Krulec7d1d6832018-12-27 11:10:09 -08004796void SurfaceFlinger::repaintEverythingForHWC() {
4797 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004798 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004799}
4800
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004801// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4802class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004803public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004804 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4805 ~WindowDisconnector() {
4806 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004807 }
4808
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004809private:
4810 ANativeWindow* mWindow;
4811 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004812};
4813
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004814status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004815 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4816 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004817 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004818 uint32_t reqWidth, uint32_t reqHeight,
4819 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004820 ISurfaceComposer::Rotation rotation,
4821 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004822 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004823
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004824 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004825
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004826 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4827
Chia-I Wu20261cb2018-08-23 12:55:44 -07004828 sp<DisplayDevice> display;
4829 {
4830 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004831
Chia-I Wu20261cb2018-08-23 12:55:44 -07004832 display = getDisplayDeviceLocked(displayToken);
4833 if (!display) return BAD_VALUE;
4834
Chia-I Wucb023152018-08-28 12:57:23 -07004835 // set the requested width/height to the logical display viewport size
4836 // by default
4837 if (reqWidth == 0 || reqHeight == 0) {
4838 reqWidth = uint32_t(display->getViewport().width());
4839 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004840 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004841 }
4842
Peiyong Lin0e003c92018-09-17 11:09:51 -07004843 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004844 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004845
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004846 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4847 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004848 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004849 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004850}
4851
chaviw93df2ea2019-04-30 16:45:12 -07004852static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4853 switch (colorMode) {
4854 case ColorMode::DISPLAY_P3:
4855 case ColorMode::BT2100_PQ:
4856 case ColorMode::BT2100_HLG:
4857 case ColorMode::DISPLAY_BT2020:
4858 return Dataspace::DISPLAY_P3;
4859 default:
4860 return Dataspace::V0_SRGB;
4861 }
4862}
4863
4864const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4865 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4866 if (displayToken) {
4867 return getDisplayDeviceLocked(displayToken);
4868 }
4869 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4870 // may not have a displayId.
4871 for (const auto& [token, display] : mDisplays) {
4872 if (display->getLayerStack() == displayOrLayerStack) {
4873 return display;
4874 }
4875 }
4876 return nullptr;
4877}
4878
4879status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4880 sp<GraphicBuffer>* outBuffer) {
4881 sp<DisplayDevice> display;
4882 uint32_t width;
4883 uint32_t height;
4884 ui::Transform::orientation_flags captureOrientation;
4885 {
4886 Mutex::Autolock _l(mStateLock);
4887 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4888 if (!display) {
4889 return BAD_VALUE;
4890 }
4891
4892 width = uint32_t(display->getViewport().width());
4893 height = uint32_t(display->getViewport().height());
4894
4895 captureOrientation = fromSurfaceComposerRotation(
4896 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004897 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4898 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4899 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4900 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4901 }
chaviw93df2ea2019-04-30 16:45:12 -07004902 *outDataspace =
4903 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4904 }
4905
4906 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4907 false /* captureSecureLayers */);
4908
4909 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4910 std::placeholders::_1);
4911 bool ignored = false;
4912 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4913 false /* useIdentityTransform */,
4914 ignored /* outCapturedSecureLayers */);
4915}
4916
Robert Carr866455f2019-04-02 16:28:26 -07004917status_t SurfaceFlinger::captureLayers(
4918 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4919 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4920 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4921 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004922 ATRACE_CALL();
4923
4924 class LayerRenderArea : public RenderArea {
4925 public:
Robert Carr578038f2018-03-09 12:25:24 -08004926 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004927 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4928 bool childrenOnly)
4929 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004930 mLayer(layer),
4931 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004932 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004933 mFlinger(flinger),
4934 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004935 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004936 Rect getBounds() const override {
4937 const Layer::State& layerState(mLayer->getDrawingState());
4938 return mLayer->getBufferSize(layerState);
4939 }
Marissa Wall61c58622018-07-18 10:12:20 -07004940 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004941 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004942 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004943 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004944 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004945 }
chaviwa76b2712017-09-20 12:02:26 -07004946 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004947 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004948 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004949 Rect getSourceCrop() const override {
4950 if (mCrop.isEmpty()) {
4951 return getBounds();
4952 } else {
4953 return mCrop;
4954 }
4955 }
Robert Carr578038f2018-03-09 12:25:24 -08004956 class ReparentForDrawing {
4957 public:
4958 const sp<Layer>& oldParent;
4959 const sp<Layer>& newParent;
4960
Vishnu Nair4351ad52019-02-11 14:13:02 -08004961 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
4962 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08004963 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08004964 // Compute and cache the bounds for the new parent layer.
4965 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07004966 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004967 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08004968 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004969 };
4970
4971 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004972 const Rect sourceCrop = getSourceCrop();
4973 // no need to check rotation because there is none
4974 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
4975 sourceCrop.height() != getReqHeight();
4976
Robert Carr578038f2018-03-09 12:25:24 -08004977 if (!mChildrenOnly) {
4978 mTransform = mLayer->getTransform().inverse();
4979 drawLayers();
4980 } else {
4981 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07004982 // In the "childrenOnly" case we reparent the children to a screenshot
4983 // layer which has no properties set and which does not draw.
4984 sp<ContainerLayer> screenshotParentLayer =
4985 mFlinger->getFactory().createContainerLayer(
4986 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
4987 bounds.getWidth(), bounds.getHeight(), 0,
4988 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08004989
Vishnu Nair4351ad52019-02-11 14:13:02 -08004990 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08004991 drawLayers();
4992 }
4993 }
chaviwa76b2712017-09-20 12:02:26 -07004994
chaviwa76b2712017-09-20 12:02:26 -07004995 private:
chaviw7206d492017-11-10 16:16:12 -08004996 const sp<Layer> mLayer;
4997 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08004998
Peiyong Linefefaac2018-08-17 12:27:51 -07004999 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005000 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005001
5002 SurfaceFlinger* mFlinger;
5003 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005004 };
5005
Robert Carrc0df3122019-04-11 13:18:21 -07005006 int reqWidth = 0;
5007 int reqHeight = 0;
5008 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005009 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005010 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005011
Robert Carrc0df3122019-04-11 13:18:21 -07005012 {
5013 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005014
Robert Carrc0df3122019-04-11 13:18:21 -07005015 parent = fromHandle(layerHandleBinder);
5016 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5017 ALOGE("captureLayers called with an invalid or removed parent");
5018 return NAME_NOT_FOUND;
5019 }
5020
5021 const int uid = IPCThreadState::self()->getCallingUid();
5022 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5023 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5024 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5025 return PERMISSION_DENIED;
5026 }
5027
5028 if (sourceCrop.width() <= 0) {
5029 crop.left = 0;
5030 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5031 }
5032
5033 if (sourceCrop.height() <= 0) {
5034 crop.top = 0;
5035 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5036 }
5037 reqWidth = crop.width() * frameScale;
5038 reqHeight = crop.height() * frameScale;
5039
5040 for (const auto& handle : excludeHandles) {
5041 sp<Layer> excludeLayer = fromHandle(handle);
5042 if (excludeLayer != nullptr) {
5043 excludeLayers.emplace(excludeLayer);
5044 } else {
5045 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5046 return NAME_NOT_FOUND;
5047 }
5048 }
5049 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005050
Chia-I Wu20261cb2018-08-23 12:55:44 -07005051 // really small crop or frameScale
5052 if (reqWidth <= 0) {
5053 reqWidth = 1;
5054 }
5055 if (reqHeight <= 0) {
5056 reqHeight = 1;
5057 }
5058
Robert Carr866455f2019-04-02 16:28:26 -07005059 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5060 auto traverseLayers = [parent, childrenOnly,
5061 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005062 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5063 if (!layer->isVisible()) {
5064 return;
Robert Carr578038f2018-03-09 12:25:24 -08005065 } else if (childrenOnly && layer == parent.get()) {
5066 return;
chaviwa76b2712017-09-20 12:02:26 -07005067 }
Robert Carr866455f2019-04-02 16:28:26 -07005068
5069 sp<Layer> p = layer;
5070 while (p != nullptr) {
5071 if (excludeLayers.count(p) != 0) {
5072 return;
5073 }
5074 p = p->getParent();
5075 }
5076
chaviwa76b2712017-09-20 12:02:26 -07005077 visitor(layer);
5078 });
5079 };
Robert Carr108b2c72019-04-02 16:32:58 -07005080
5081 bool outCapturedSecureLayers = false;
5082 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5083 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005084}
5085
5086status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5087 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005088 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005089 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005090 bool useIdentityTransform,
5091 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005092 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005093
Peiyong Lin0e003c92018-09-17 11:09:51 -07005094 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005095 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5096 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005097 *outBuffer =
5098 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5099 static_cast<android_pixel_format>(reqPixelFormat), 1,
5100 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005101
Robert Carr108b2c72019-04-02 16:32:58 -07005102 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5103 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005104}
5105
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005106status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5107 TraverseLayersFunction traverseLayers,
5108 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005109 bool useIdentityTransform,
5110 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005111 // This mutex protects syncFd and captureResult for communication of the return values from the
5112 // main thread back to this Binder thread
5113 std::mutex captureMutex;
5114 std::condition_variable captureCondition;
5115 std::unique_lock<std::mutex> captureLock(captureMutex);
5116 int syncFd = -1;
5117 std::optional<status_t> captureResult;
5118
Robert Carr03480e22018-01-04 16:02:06 -08005119 const int uid = IPCThreadState::self()->getCallingUid();
5120 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5121
Dominik Laskowski8c001672018-05-30 16:52:06 -07005122 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005123 // If there is a refresh pending, bug out early and tell the binder thread to try again
5124 // after the refresh.
5125 if (mRefreshPending) {
5126 ATRACE_NAME("Skipping screenshot for now");
5127 std::unique_lock<std::mutex> captureLock(captureMutex);
5128 captureResult = std::make_optional<status_t>(EAGAIN);
5129 captureCondition.notify_one();
5130 return;
5131 }
5132
5133 status_t result = NO_ERROR;
5134 int fd = -1;
5135 {
5136 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005137 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005138 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005139 useIdentityTransform, forSystem, &fd,
5140 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005141 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005142 }
5143
5144 {
5145 std::unique_lock<std::mutex> captureLock(captureMutex);
5146 syncFd = fd;
5147 captureResult = std::make_optional<status_t>(result);
5148 captureCondition.notify_one();
5149 }
5150 });
5151
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005152 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005153 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005154 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005155 while (*captureResult == EAGAIN) {
5156 captureResult.reset();
5157 result = postMessageAsync(message);
5158 if (result != NO_ERROR) {
5159 return result;
5160 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005161 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005162 }
5163 result = *captureResult;
5164 }
5165
5166 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005167 sync_wait(syncFd, -1);
5168 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005169 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005170
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005171 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005172}
5173
chaviwa76b2712017-09-20 12:02:26 -07005174void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005175 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005176 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5177 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005178 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005179
chaviwa76b2712017-09-20 12:02:26 -07005180 const auto reqWidth = renderArea.getReqWidth();
5181 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005182 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005183 const auto transform = renderArea.getTransform();
5184 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005185
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005186 renderengine::DisplaySettings clientCompositionDisplay;
5187 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005188
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005189 // assume that bounds are never offset, and that they are the same as the
5190 // buffer bounds.
5191 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005192 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005193 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005194
5195 // Now take into account the rotation flag. We append a transform that
5196 // rotates the layer stack about the origin, then translate by buffer
5197 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005198 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005199 int displacementX = 0;
5200 int displacementY = 0;
5201 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5202 switch (rotation) {
5203 case ui::Transform::ROT_90:
5204 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005205 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005206 break;
5207 case ui::Transform::ROT_180:
5208 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005209 displacementY = renderArea.getBounds().getWidth();
5210 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005211 break;
5212 case ui::Transform::ROT_270:
5213 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005214 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005215 break;
5216 default:
5217 break;
5218 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005219
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005220 // We need to transform the clipping window into the right spot.
5221 // First, rotate the clipping rectangle by the rotation hint to get the
5222 // right orientation
5223 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5224 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5225 const vec4 rotClipTL = rotMatrix * clipTL;
5226 const vec4 rotClipBR = rotMatrix * clipBR;
5227 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5228 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5229 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5230 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5231
5232 // Now reposition the clipping rectangle with the displacement vector
5233 // computed above.
5234 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005235 clientCompositionDisplay.clip =
5236 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5237 newClipRight + displacementX, newClipBottom + displacementY);
5238
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005239 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005240 clientCompositionDisplay.globalTransform =
5241 clipTransform * clientCompositionDisplay.globalTransform;
5242
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005243 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5244 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005245
chaviw50da5042018-04-09 13:49:37 -07005246 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005247
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005248 renderengine::LayerSettings fillLayer;
5249 fillLayer.source.buffer.buffer = nullptr;
5250 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5251 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5252 fillLayer.alpha = half(alpha);
5253 clientCompositionLayers.push_back(fillLayer);
5254
5255 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005256 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005257 const bool supportProtectedContent = false;
5258 Region clip(renderArea.getBounds());
5259 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5260 clip,
5261 useIdentityTransform,
5262 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5263 renderArea.isSecure(),
5264 supportProtectedContent,
5265 clearRegion,
5266 };
5267 auto result = layer->prepareClientComposition(targetSettings);
5268 if (result) {
5269 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005270 }
chaviwa76b2712017-09-20 12:02:26 -07005271 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005272
5273 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005274 // Use an empty fence for the buffer fence, since we just created the buffer so
5275 // there is no need for synchronization with the GPU.
5276 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005277 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005278 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005279 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005280 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005281
5282 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005283}
5284
chaviwa76b2712017-09-20 12:02:26 -07005285status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5286 TraverseLayersFunction traverseLayers,
5287 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005288 bool useIdentityTransform, bool forSystem,
5289 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005290 ATRACE_CALL();
5291
chaviwa76b2712017-09-20 12:02:26 -07005292 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005293 outCapturedSecureLayers =
5294 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005295 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005296
Robert Carr03480e22018-01-04 16:02:06 -08005297 // We allow the system server to take screenshots of secure layers for
5298 // use in situations like the Screen-rotation animation and place
5299 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005300 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005301 ALOGW("FB is protected: PERMISSION_DENIED");
5302 return PERMISSION_DENIED;
5303 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005304 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005306}
5307
chaviw95ef3c42019-02-14 10:55:09 -08005308void SurfaceFlinger::setInputWindowsFinished() {
5309 Mutex::Autolock _l(mStateLock);
5310
5311 mPendingSyncInputWindows = false;
5312 mTransactionCV.broadcast();
5313}
chaviw5f21a5e2019-02-14 10:00:34 -08005314
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005315// ---------------------------------------------------------------------------
5316
Dan Stoza412903f2017-04-27 13:42:17 -07005317void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5318 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005319}
5320
Dan Stoza412903f2017-04-27 13:42:17 -07005321void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5322 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005323}
5324
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005325void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005326 const LayerVector::Visitor& visitor) {
5327 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005328 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005329 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005330 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005331 continue;
5332 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005333 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005334 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005335 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005336 return;
5337 }
chaviwa76b2712017-09-20 12:02:26 -07005338 if (!layer->isVisible()) {
5339 return;
5340 }
5341 visitor(layer);
5342 });
5343 }
5344}
5345
Dominik Laskowski22488f62019-03-28 09:53:04 -07005346void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5347 const std::vector<int32_t>& allowedConfigs) {
5348 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005349 return;
5350 }
5351
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005352 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5353 allowedConfigs.end());
5354 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5355 return;
5356 }
5357
Ady Abraham838de062019-02-04 10:24:03 -08005358 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005359 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5360
5361 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5362 // that listeners that care about a change in allowed configs can get the notification.
5363 // Giving current ActiveConfig so that most other listeners would just drop the event
5364 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5365 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005366
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005367 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5368 const auto& type = mScheduler->getPreferredRefreshRateType();
5369 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5370 if (isDisplayConfigAllowed(config.configId)) {
5371 ALOGV("switching to Scheduler preferred config %d", config.configId);
5372 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5373 } else {
5374 // Set the highest allowed config by iterating backwards on available refresh rates
5375 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5376 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5377 if (isDisplayConfigAllowed(iter->second.configId)) {
5378 ALOGV("switching to allowed config %d", iter->second.configId);
5379 setDesiredActiveConfig(
5380 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5381 break;
5382 }
5383 }
5384 }
5385 } else if (!allowedConfigs.empty()) {
5386 ALOGV("switching to config %d", allowedConfigs[0]);
5387 setDesiredActiveConfig(
5388 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5389 }
Ady Abraham838de062019-02-04 10:24:03 -08005390}
5391
Dominik Laskowski22488f62019-03-28 09:53:04 -07005392status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005393 const std::vector<int32_t>& allowedConfigs) {
5394 ATRACE_CALL();
5395
Dominik Laskowski22488f62019-03-28 09:53:04 -07005396 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005397 return BAD_VALUE;
5398 }
5399
Ady Abraham34392f72019-04-10 11:29:27 -07005400 if (mDebugDisplayConfigSetByBackdoor) {
5401 // ignore this request as config is overridden by backdoor
5402 return NO_ERROR;
5403 }
5404
Ady Abraham838de062019-02-04 10:24:03 -08005405 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005406 const auto display = getDisplayDeviceLocked(displayToken);
5407 if (!display) {
5408 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5409 displayToken.get());
5410 } else if (display->isVirtual()) {
5411 ALOGW("Attempt to set allowed display configs for virtual display");
5412 } else {
5413 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5414 }
Ady Abraham838de062019-02-04 10:24:03 -08005415 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005416
Ady Abraham838de062019-02-04 10:24:03 -08005417 return NO_ERROR;
5418}
5419
Dominik Laskowski22488f62019-03-28 09:53:04 -07005420status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005421 std::vector<int32_t>* outAllowedConfigs) {
5422 ATRACE_CALL();
5423
Dominik Laskowski22488f62019-03-28 09:53:04 -07005424 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005425 return BAD_VALUE;
5426 }
5427
Dominik Laskowski22488f62019-03-28 09:53:04 -07005428 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005429
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005430 const auto display = getDisplayDeviceLocked(displayToken);
5431 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005432 return NAME_NOT_FOUND;
5433 }
5434
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005435 if (display->isPrimary()) {
5436 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5437 }
5438
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005439 return NO_ERROR;
5440}
5441
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005442void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005443 mFlinger->setInputWindowsFinished();
5444}
5445
Robert Carrc0df3122019-04-11 13:18:21 -07005446sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5447 BBinder *b = handle->localBinder();
5448 if (b == nullptr) {
5449 return nullptr;
5450 }
5451 auto it = mLayersByLocalBinderToken.find(b);
5452 if (it != mLayersByLocalBinderToken.end()) {
5453 return it->second.promote();
5454 }
5455 return nullptr;
5456}
5457
Alec Mouri4545a8a2019-08-08 20:05:32 -07005458void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5459 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5460}
5461
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005462} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005463
Mathias Agopian3f844832013-08-07 21:24:32 -07005464#if defined(__gl_h_)
5465#error "don't include gl/gl.h in this file"
5466#endif
5467
5468#if defined(__gl2_h_)
5469#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005470#endif