blob: b9e95a6e46481dd8575f400e77349c3a0652d971 [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"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700111#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800112#include "android-base/stringprintf.h"
113
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800115#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
116#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700117#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900118#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
chaviw1d044282017-09-27 12:19:28 -0700120#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700124
Jaesoo Lee43518572017-01-23 19:03:16 +0900125using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900127using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800128
Ady Abraham8532d012019-05-08 14:50:56 -0700129using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700131using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700132using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800133using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700134using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700135using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900136
Steven Thomasb02664d2017-07-26 18:48:28 -0700137namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700138
139#pragma clang diagnostic push
140#pragma clang diagnostic error "-Wswitch-enum"
141
142bool isWideColorMode(const ColorMode colorMode) {
143 switch (colorMode) {
144 case ColorMode::DISPLAY_P3:
145 case ColorMode::ADOBE_RGB:
146 case ColorMode::DCI_P3:
147 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700148 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700149 case ColorMode::BT2100_PQ:
150 case ColorMode::BT2100_HLG:
151 return true;
152 case ColorMode::NATIVE:
153 case ColorMode::STANDARD_BT601_625:
154 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
155 case ColorMode::STANDARD_BT601_525:
156 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
157 case ColorMode::STANDARD_BT709:
158 case ColorMode::SRGB:
159 return false;
160 }
161 return false;
162}
163
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700164ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
165 switch (rotation) {
166 case ISurfaceComposer::eRotateNone:
167 return ui::Transform::ROT_0;
168 case ISurfaceComposer::eRotate90:
169 return ui::Transform::ROT_90;
170 case ISurfaceComposer::eRotate180:
171 return ui::Transform::ROT_180;
172 case ISurfaceComposer::eRotate270:
173 return ui::Transform::ROT_270;
174 }
175 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
176 return ui::Transform::ROT_0;
177}
178
Peiyong Linfca547f2018-07-09 13:03:33 -0700179#pragma clang diagnostic pop
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181class ConditionalLock {
182public:
183 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
184 if (lock) {
185 mMutex.lock();
186 }
187 }
188 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
189private:
190 Mutex& mMutex;
191 bool mLocked;
192};
Peiyong Linfca547f2018-07-09 13:03:33 -0700193
Peiyong Lin9d846a52018-11-05 13:18:20 -0800194// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
195bool validateCompositionDataspace(Dataspace dataspace) {
196 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
197}
198
Steven Thomasb02664d2017-07-26 18:48:28 -0700199} // namespace anonymous
200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201// ---------------------------------------------------------------------------
202
Mathias Agopian99b49842011-06-27 16:05:52 -0700203const String16 sHardwareTest("android.permission.HARDWARE_TEST");
204const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
205const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
206const String16 sDump("android.permission.DUMP");
207
208// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700210bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800211uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800212bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800213bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800214int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600215bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700216int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700217bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700218bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700219Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
220ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
221Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700223
Kalle Raitaa099a242017-01-11 11:17:29 -0800224std::string getHwcServiceName() {
225 char value[PROPERTY_VALUE_MAX] = {};
226 property_get("debug.sf.hwc_service_name", value, "default");
227 ALOGI("Using HWComposer service: '%s'", value);
228 return std::string(value);
229}
230
231bool useTrebleTestingOverride() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.treble_testing_override", value, "false");
234 ALOGI("Treble testing override: '%s'", value);
235 return std::string(value) == "true";
236}
237
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800238std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
239 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800240 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700241 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Enhanced");
246 default:
247 return std::string("Unknown ") +
248 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250}
251
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700252SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
255 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700257 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700258 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700259 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700260 mCompositionEngine(mFactory.createCompositionEngine()),
261 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800262
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700263SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800265
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900266 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900268 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700269
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900270 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700271
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900272 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273
Steven Thomas050b2c82017-03-06 11:45:16 -0800274 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600282
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 mDefaultCompositionDataspace =
284 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700285 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
286 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 defaultCompositionDataspace = mDefaultCompositionDataspace;
288 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
289 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
290 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
291 wideColorGamutCompositionPixelFormat =
292 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700293
Yichi Chenda901bf2019-06-28 14:58:27 +0800294 mColorSpaceAgnosticDataspace =
295 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
300 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
301 switch (tmpPrimaryDisplayOrientation) {
302 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700303 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800304 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
311 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700315 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800316
Sundong Ahn85131bd2019-02-18 15:51:53 +0900317 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800318
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 // debugging stuff...
320 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700321
Mathias Agopianb4b17302013-03-20 18:36:41 -0700322 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700323 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700324
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325 property_get("debug.sf.showupdates", value, "0");
326 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700327
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700328 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000329
330 // DDMS debugging deprecated (b/120782499)
331 property_get("debug.sf.ddms", value, "0");
332 int debugDdms = atoi(value);
333 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700334
335 property_get("debug.sf.disable_backpressure", value, "0");
336 mPropagateBackpressure = !atoi(value);
337 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700338
Ady Abrahamadb9a992019-09-19 21:21:55 +0000339 property_get("debug.sf.enable_gl_backpressure", value, "0");
340 mPropagateBackpressureClientComposition = atoi(value);
341 ALOGI_IF(mPropagateBackpressureClientComposition,
342 "Enabling backpressure propagation for Client Composition");
343
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800344 property_get("debug.sf.enable_hwc_vds", value, "0");
345 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800346 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800347
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800348 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800349 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800350 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700351
Yiwei Zhang243b3782018-05-15 17:40:04 -0700352 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700353 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
354 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
355
Ana Krulece5a06e02019-03-06 17:09:03 -0800356 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800357 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800358
359 int int_value = atoi(value);
360 if (int_value) {
361 mUseSmart90ForVideo = true;
362 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800363
Dan Stozaec460082018-12-17 15:35:09 -0800364 property_get("debug.sf.luma_sampling", value, "1");
365 mLumaSampling = atoi(value);
366
Romain Guy11d63f42017-07-20 12:47:14 -0700367 // We should be reading 'persist.sys.sf.color_saturation' here
368 // but since /data may be encrypted, we need to wait until after vold
369 // comes online to attempt to read the property. The property is
370 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800371
372 if (useTrebleTestingOverride()) {
373 // Without the override SurfaceFlinger cannot connect to HIDL
374 // services that are not listed in the manifests. Considered
375 // deriving the setting from the set service name, but it
376 // would be brittle if the name that's not 'default' is used
377 // for production purposes later on.
378 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380}
381
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800382void SurfaceFlinger::onFirstRef()
383{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800384 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385}
386
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700387SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388
Dan Stozac7014012014-02-14 15:03:43 -0800389void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390{
391 // the window manager died on us. prepare its eulogy.
392
Andy McFadden13a082e2012-08-24 10:16:42 -0700393 // restore initial conditions (default device unblank, etc)
394 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395
396 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700397 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Robert Carr1db73f62016-12-21 12:58:51 -0800400static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700401 status_t err = client->initCheck();
402 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800403 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404 }
Robert Carr1db73f62016-12-21 12:58:51 -0800405 return nullptr;
406}
407
408sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
409 return initClient(new Client(this));
410}
411
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700412sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
413 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414{
415 class DisplayToken : public BBinder {
416 sp<SurfaceFlinger> flinger;
417 virtual ~DisplayToken() {
418 // no more references, this display must be terminated
419 Mutex::Autolock _l(flinger->mStateLock);
420 flinger->mCurrentState.displays.removeItem(this);
421 flinger->setTransactionFlags(eDisplayTransactionNeeded);
422 }
423 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700424 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700425 : flinger(flinger) {
426 }
427 };
428
429 sp<BBinder> token = new DisplayToken(this);
430
431 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700432 // Display ID is assigned when virtual display is allocated by HWC.
433 DisplayDeviceState state;
434 state.isSecure = secure;
435 state.displayName = displayName;
436 mCurrentState.displays.add(token, state);
437 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 return token;
439}
440
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700441void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 Mutex::Autolock _l(mStateLock);
443
Dominik Laskowski075d3172018-05-24 15:50:06 -0700444 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
445 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700446 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 return;
448 }
449
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
451 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 ALOGE("destroyDisplay called for non-virtual display");
453 return;
454 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700455 mInterceptor->saveDisplayDeletion(state.sequenceId);
456 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 setTransactionFlags(eDisplayTransactionNeeded);
458}
459
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800460std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
461 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463 const auto internalDisplayId = getInternalDisplayIdLocked();
464 if (!internalDisplayId) {
465 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 }
467
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800468 std::vector<PhysicalDisplayId> displayIds;
469 displayIds.reserve(mPhysicalDisplayTokens.size());
470 displayIds.push_back(internalDisplayId->value);
471
472 for (const auto& [id, token] : mPhysicalDisplayTokens) {
473 if (id != *internalDisplayId) {
474 displayIds.push_back(id.value);
475 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478 return displayIds;
479}
480
481sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
482 Mutex::Autolock lock(mStateLock);
483 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484}
485
Ady Abraham37965d42018-11-01 13:43:32 -0700486status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
487 if (!outGetColorManagement) {
488 return BAD_VALUE;
489 }
490 *outGetColorManagement = useColorManagement;
491 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700492}
493
Lloyd Pique441d5042018-10-18 16:49:51 -0700494HWComposer& SurfaceFlinger::getHwComposer() const {
495 return mCompositionEngine->getHwComposer();
496}
497
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700498renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
499 return mCompositionEngine->getRenderEngine();
500}
501
Lloyd Pique70d91362018-10-18 16:02:55 -0700502compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
503 return *mCompositionEngine.get();
504}
505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506void SurfaceFlinger::bootFinished()
507{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700508 if (mStartPropertySetThread->join() != NO_ERROR) {
509 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800511 const nsecs_t now = systemTime();
512 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000513 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700514
Mikael Pessa90092f42019-08-26 17:22:04 -0700515 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700516
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 // wait patiently for the window manager death
518 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700519 mWindowManager = defaultServiceManager()->getService(name);
520 if (mWindowManager != 0) {
521 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700522 }
Robert Carr720e5062018-07-30 17:45:14 -0700523 sp<IBinder> input(defaultServiceManager()->getService(
524 String16("inputflinger")));
525 if (input == nullptr) {
526 ALOGE("Failed to link to input service");
527 } else {
528 mInputFlinger = interface_cast<IInputFlinger>(input);
529 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 if (mVrFlinger) {
532 mVrFlinger->OnBootFinished();
533 }
534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700536 // formerly we would just kill the process, but we now ask it to exit so it
537 // can choose where to stop the animation.
538 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700539
540 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
541 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
542 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700543
Ana Krulecbd6654b2019-02-15 15:18:15 -0800544 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800545 readPersistentProperties();
546 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800547
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700548 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
549 // set the refresh rate according to the policy
550 const auto& performanceRefreshRate =
551 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800552
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700553 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
554 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
555 } else {
556 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
557 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800559 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
Dan Stoza436ccf32018-06-21 12:10:12 -0700562uint32_t SurfaceFlinger::getNewTexture() {
563 {
564 std::lock_guard lock(mTexturePoolMutex);
565 if (!mTexturePool.empty()) {
566 uint32_t name = mTexturePool.back();
567 mTexturePool.pop_back();
568 ATRACE_INT("TexturePoolSize", mTexturePool.size());
569 return name;
570 }
571
572 // The pool was too small, so increase it for the future
573 ++mTexturePoolSize;
574 }
575
576 // The pool was empty, so we need to get a new texture name directly using a
577 // blocking call to the main thread
578 uint32_t name = 0;
579 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
580 return name;
581}
582
Mathias Agopian3f844832013-08-07 21:24:32 -0700583void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700584 std::lock_guard lock(mTexturePoolMutex);
585 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
586 // to actually delete this or not based on mTexturePoolSize
587 mTexturePool.push_back(texture);
588 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700589}
590
Wei Wangf9b05ee2017-07-19 20:59:39 -0700591// Do not call property_set on main thread which will be blocked by init
592// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700594 ALOGI( "SurfaceFlinger's main thread ready to run. "
595 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700596 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700601 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700602 renderEngineFeature |= (useColorManagement ?
603 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700604 renderEngineFeature |= (useContextPriority ?
605 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700606 renderEngineFeature |=
607 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
608 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700609
610 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800611 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700612 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700613 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800614 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700615
616 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
617 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700618 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
619 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800620 // Process any initial hotplug and resulting display changes.
621 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700622 const auto display = getDefaultDisplayDeviceLocked();
623 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700624 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700625 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800626
Steven Thomas050b2c82017-03-06 11:45:16 -0800627 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700629 // This callback is called from the vr flinger dispatch thread. We
630 // need to call signalTransaction(), which requires holding
631 // mStateLock when we're not on the main thread. Acquiring
632 // mStateLock from the vr flinger dispatch thread might trigger a
633 // deadlock in surface flinger (see b/66916578), so post a message
634 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700636 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
637 mVrFlingerRequestsDisplay = requestDisplay;
638 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
642 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700643 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700644 .value_or(0),
645 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (!mVrFlinger) {
647 ALOGE("Failed to start vrflinger");
648 }
649 }
650
Mathias Agopian92a979a2012-08-02 18:32:23 -0700651 // initialize our drawing state
652 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700653
Andy McFadden13a082e2012-08-24 10:16:42 -0700654 // set initial conditions (e.g. unblank default device)
655 initializeDisplays();
656
Steven Thomas137d4bc2019-07-25 16:55:14 -0700657 char primeShaderCache[PROPERTY_VALUE_MAX];
658 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
659 if (atoi(primeShaderCache)) {
660 getRenderEngine().primeCache();
661 }
Dan Stoza4e637772016-07-28 13:31:51 -0700662
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700664
665 const bool presentFenceReliable =
666 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
667 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700668
669 if (mStartPropertySetThread->Start() != NO_ERROR) {
670 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700674}
675
Romain Guy11d63f42017-07-20 12:47:14 -0700676void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700677 Mutex::Autolock _l(mStateLock);
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679 char value[PROPERTY_VALUE_MAX];
680
681 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800682 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700683 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800684 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100685
686 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700687 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800688
689 property_get("persist.sys.sf.color_mode", value, "0");
690 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700691}
692
Mathias Agopiana67e4182012-06-19 17:26:12 -0700693void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800694 // Start boot animation service by setting a property mailbox
695 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700696 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800697 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 if (mStartPropertySetThread->join() != NO_ERROR) {
699 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700701}
702
Mathias Agopian875d8e12013-06-07 15:35:48 -0700703size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700704 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700705}
706
Mathias Agopian875d8e12013-06-07 15:35:48 -0700707size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700708 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700709}
710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800711// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800712
Jamie Gennis582270d2011-08-17 18:19:00 -0700713bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800715 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800716 return authenticateSurfaceTextureLocked(bufferProducer);
717}
718
719bool SurfaceFlinger::authenticateSurfaceTextureLocked(
720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800721 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800722 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800723}
724
Brian Anderson6b376712017-04-04 10:51:39 -0700725status_t SurfaceFlinger::getSupportedFrameTimestamps(
726 std::vector<FrameEvent>* outSupported) const {
727 *outSupported = {
728 FrameEvent::REQUESTED_PRESENT,
729 FrameEvent::ACQUIRE,
730 FrameEvent::LATCH,
731 FrameEvent::FIRST_REFRESH_START,
732 FrameEvent::LAST_REFRESH_START,
733 FrameEvent::GPU_COMPOSITION_DONE,
734 FrameEvent::DEQUEUE_READY,
735 FrameEvent::RELEASE,
736 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700737 ConditionalLock _l(mStateLock,
738 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700739 if (!getHwComposer().hasCapability(
740 HWC2::Capability::PresentFenceIsNotReliable)) {
741 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
742 }
743 return NO_ERROR;
744}
745
Dominik Laskowski22488f62019-03-28 09:53:04 -0700746status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
747 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700748 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 return BAD_VALUE;
750 }
751
Dominik Laskowski22488f62019-03-28 09:53:04 -0700752 Mutex::Autolock lock(mStateLock);
753
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800754 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700755 if (!displayId) {
756 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700757 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 // TODO: Not sure if display density should handled by SF any longer
760 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700761 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700763 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800764 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700765 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700766 }
767 return density;
768 }
769 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700770 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700771 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700772 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700773 return getDensityFromProperty("ro.sf.lcd_density"); }
774 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700775
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700777
Dominik Laskowski075d3172018-05-24 15:50:06 -0700778 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 DisplayInfo info = DisplayInfo();
780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781 float xdpi = hwConfig->getDpiX();
782 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700783
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700784 info.w = hwConfig->getWidth();
785 info.h = hwConfig->getHeight();
786 // Default display viewport to display width and height
787 info.viewportW = info.w;
788 info.viewportH = info.h;
789
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800790 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 // The density of the device is provided by a build property
792 float density = Density::getBuildDensity() / 160.0f;
793 if (density == 0) {
794 // the build doesn't provide a density -- this is wrong!
795 // use xdpi instead
796 ALOGE("ro.sf.lcd_density must be defined as a build property");
797 density = xdpi / 160.0f;
798 }
799 if (Density::getEmuDensity()) {
800 // if "qemu.sf.lcd_density" is specified, it overrides everything
801 xdpi = ydpi = density = Density::getEmuDensity();
802 density /= 160.0f;
803 }
804 info.density = density;
805
806 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807 const auto display = getDefaultDisplayDeviceLocked();
808 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700809
810 // This is for screenrecord
811 const Rect viewport = display->getViewport();
812 if (viewport.isValid()) {
813 info.viewportW = uint32_t(viewport.getWidth());
814 info.viewportH = uint32_t(viewport.getHeight());
815 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700816 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 } else {
818 // TODO: where should this value come from?
819 static const int TV_DENSITY = 213;
820 info.density = TV_DENSITY / 160.0f;
821 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700822
823 const auto display = getDisplayDeviceLocked(displayToken);
824 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 }
826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 info.xdpi = xdpi;
828 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700830 const auto refreshRateType =
831 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700832 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
833 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834
Andy McFadden91b2ca82014-06-13 14:04:23 -0700835 // This is how far in advance a buffer must be queued for
836 // presentation at a given time. If you want a buffer to appear
837 // on the screen at time N, you must submit the buffer before
838 // (N - presentationDeadline).
839 //
840 // Normally it's one full refresh period (to give SF a chance to
841 // latch the buffer), but this can be reduced by configuring a
842 // DispSync offset. Any additional delays introduced by the hardware
843 // composer or panel must be accounted for here.
844 //
845 // We add an additional 1ms to allow for processing time and
846 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700847 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700848
849 // All non-virtual displays are currently considered secure.
850 info.secure = true;
851
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800852 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700853 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800854 std::swap(info.w, info.h);
855 }
856
Michael Wright28f24d02016-07-12 13:30:53 -0700857 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700858 }
859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 return NO_ERROR;
861}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700862
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
864 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700865 return BAD_VALUE;
866 }
867
Ana Krulecc2870422019-01-29 19:00:58 -0800868 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 return NO_ERROR;
870}
871
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700872int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
873 const auto display = getDisplayDevice(displayToken);
874 if (!display) {
875 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800876 return BAD_VALUE;
877 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700878
Steven Thomasc9098452019-09-30 17:15:05 -0700879 if (display->isPrimary()) {
880 std::lock_guard<std::mutex> lock(mActiveConfigLock);
881 if (mDesiredActiveConfigChanged) {
882 return mDesiredActiveConfig.configId;
883 } else {
884 return display->getActiveConfig();
885 }
886 } else {
887 return display->getActiveConfig();
888 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700889}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700890
Ady Abraham03b02dd2019-03-21 15:40:11 -0700891void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800892 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800893
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800894 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800895 // config twice. However event generation config might have changed so we need to update it
896 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800897 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700898 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
899 mDesiredActiveConfig = info;
900 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800901
902 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800903 // This will trigger HWC refresh without resetting the idle timer.
904 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700905 // Start receiving vsync samples now, so that we can detect a period
906 // switch.
907 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700908 // As we called to set period, we will call to onRefreshRateChangeCompleted once
909 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700910 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700911 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700912 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800913 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800914 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700915
916 if (mRefreshRateOverlay) {
917 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
918 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800919}
920
921status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
922 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800923
924 std::vector<int32_t> allowedConfig;
925 allowedConfig.push_back(mode);
926
927 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928}
929
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800930void SurfaceFlinger::setActiveConfigInternal() {
931 ATRACE_CALL();
932
Dominik Laskowski22488f62019-03-28 09:53:04 -0700933 const auto display = getDefaultDisplayDeviceLocked();
934 if (!display) {
935 return;
936 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800937
Dominik Laskowski22488f62019-03-28 09:53:04 -0700938 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700939 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
940 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700941
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942 display->setActiveConfig(mUpcomingActiveConfig.configId);
943
Alec Mouri754c98a2019-03-18 18:53:42 -0700944 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700945 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700947
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800948 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800949 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
950 mUpcomingActiveConfig.configId);
951 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800952}
953
Ady Abraham53852a52019-05-28 18:07:44 -0700954void SurfaceFlinger::desiredActiveConfigChangeDone() {
955 std::lock_guard<std::mutex> lock(mActiveConfigLock);
956 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
957 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700958
959 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
960 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700961 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700962}
963
Dominik Laskowski22488f62019-03-28 09:53:04 -0700964bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800965 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800966 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700967 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700969 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800970 return true;
971 }
972
973 // We received the present fence from the HWC, so we assume it successfully updated
974 // the config, hence we update SF.
975 mCheckPendingFence = false;
976 setActiveConfigInternal();
977 }
978
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 // Store the local variable to release the lock.
980 ActiveConfigInfo desiredActiveConfig;
981 {
982 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 if (!mDesiredActiveConfigChanged) {
984 return false;
985 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986 desiredActiveConfig = mDesiredActiveConfig;
987 }
988
Dominik Laskowski22488f62019-03-28 09:53:04 -0700989 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800990 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
991 // display is not valid or we are already in the requested mode
992 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700993 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800994 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800996
Ady Abraham838de062019-02-04 10:24:03 -0800997 // Desired active config was set, it is different than the config currently in use, however
998 // allowed configs might have change by the time we process the refresh.
999 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001000 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001001 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001002 return false;
1003 }
Alec Mouri7f015182019-07-11 13:56:22 -07001004
Ady Abrahamb838aed2019-02-12 15:30:16 -08001005 mUpcomingActiveConfig = desiredActiveConfig;
1006 const auto displayId = display->getId();
1007 LOG_ALWAYS_FATAL_IF(!displayId);
1008
1009 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1010 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1011
1012 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001014 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001015 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001016}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1019 Vector<ColorMode>* outColorModes) {
1020 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001021 return BAD_VALUE;
1022 }
1023
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001025 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001026 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001027 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1028
1029 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1030 if (!displayId) {
1031 return NAME_NOT_FOUND;
1032 }
1033
Dominik Laskowski075d3172018-05-24 15:50:06 -07001034 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001035 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001036 }
Michael Wright28f24d02016-07-12 13:30:53 -07001037 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001038
1039 // If it's built-in display and the configuration claims it's not wide color capable,
1040 // filter out all wide color modes. The typical reason why this happens is that the
1041 // hardware is not good enough to support GPU composition of wide color, and thus the
1042 // OEMs choose to disable this capability.
1043 if (isInternalDisplay && !hasWideColorDisplay) {
1044 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1045 isWideColorMode);
1046 } else {
1047 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1048 }
Michael Wright28f24d02016-07-12 13:30:53 -07001049
1050 return NO_ERROR;
1051}
1052
Daniel Solomon42d04562019-01-20 21:03:19 -08001053status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1054 ui::DisplayPrimaries &primaries) {
1055 if (!displayToken) {
1056 return BAD_VALUE;
1057 }
1058
1059 // Currently we only support this API for a single internal display.
1060 if (getInternalDisplayToken() != displayToken) {
1061 return BAD_VALUE;
1062 }
1063
1064 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1065 return NO_ERROR;
1066}
1067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1069 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001070 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001072 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001073}
1074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001076 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001077 Vector<ColorMode> modes;
1078 getDisplayColorModes(displayToken, &modes);
1079 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1080 if (mode < ColorMode::NATIVE || !exists) {
1081 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1082 decodeColorMode(mode).c_str(), mode, displayToken.get());
1083 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001084 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085 const auto display = getDisplayDevice(displayToken);
1086 if (!display) {
1087 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1088 decodeColorMode(mode).c_str(), mode, displayToken.get());
1089 } else if (display->isVirtual()) {
1090 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1091 decodeColorMode(mode).c_str(), mode);
1092 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001093 display->getCompositionDisplay()->setColorProfile(
1094 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1095 RenderIntent::COLORIMETRIC,
1096 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097 }
1098 }));
1099
Michael Wright28f24d02016-07-12 13:30:53 -07001100 return NO_ERROR;
1101}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001102
Svetoslavd85084b2014-03-20 10:28:31 -07001103status_t SurfaceFlinger::clearAnimationFrameStats() {
1104 Mutex::Autolock _l(mStateLock);
1105 mAnimFrameTracker.clearStats();
1106 return NO_ERROR;
1107}
1108
1109status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1110 Mutex::Autolock _l(mStateLock);
1111 mAnimFrameTracker.getStats(outStats);
1112 return NO_ERROR;
1113}
1114
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1116 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001117 Mutex::Autolock _l(mStateLock);
1118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119 const auto display = getDisplayDeviceLocked(displayToken);
1120 if (!display) {
1121 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001122 return BAD_VALUE;
1123 }
1124
Peiyong Linfb069302018-04-25 14:34:31 -07001125 // At this point the DisplayDeivce should already be set up,
1126 // meaning the luminance information is already queried from
1127 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001129 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1130 capabilities.getDesiredMaxLuminance(),
1131 capabilities.getDesiredMaxAverageLuminance(),
1132 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001133
1134 return NO_ERROR;
1135}
1136
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001137status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1138 ui::PixelFormat* outFormat,
1139 ui::Dataspace* outDataspace,
1140 uint8_t* outComponentMask) const {
1141 if (!outFormat || !outDataspace || !outComponentMask) {
1142 return BAD_VALUE;
1143 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001144 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001145 if (!display || !display->getId()) {
1146 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1147 return BAD_VALUE;
1148 }
1149 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1150 outDataspace, outComponentMask);
1151}
1152
Kevin DuBois74e53772018-11-19 10:52:38 -08001153status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1154 bool enable, uint8_t componentMask,
1155 uint64_t maxFrames) const {
1156 const auto display = getDisplayDevice(displayToken);
1157 if (!display || !display->getId()) {
1158 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1159 return BAD_VALUE;
1160 }
1161
1162 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1163 componentMask, maxFrames);
1164}
1165
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001166status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1167 uint64_t maxFrames, uint64_t timestamp,
1168 DisplayedFrameStats* outStats) const {
1169 const auto display = getDisplayDevice(displayToken);
1170 if (!display || !display->getId()) {
1171 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1172 return BAD_VALUE;
1173 }
1174
1175 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1176 outStats);
1177}
1178
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001179status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1180 if (!outSupported) {
1181 return BAD_VALUE;
1182 }
1183 *outSupported = getRenderEngine().supportsProtectedContent();
1184 return NO_ERROR;
1185}
1186
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001187status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1188 bool* outIsWideColorDisplay) const {
1189 if (!displayToken || !outIsWideColorDisplay) {
1190 return BAD_VALUE;
1191 }
1192 Mutex::Autolock _l(mStateLock);
1193 const auto display = getDisplayDeviceLocked(displayToken);
1194 if (!display) {
1195 return BAD_VALUE;
1196 }
Peiyong Linff84a152019-05-17 18:36:19 -07001197
1198 // Use hasWideColorDisplay to override built-in display.
1199 const auto displayId = display->getId();
1200 if (displayId && displayId == getInternalDisplayIdLocked()) {
1201 *outIsWideColorDisplay = hasWideColorDisplay;
1202 return NO_ERROR;
1203 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001204 *outIsWideColorDisplay = display->hasWideColorGamut();
1205 return NO_ERROR;
1206}
1207
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001208status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001209 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001210 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211
Dominik Laskowski6505f792019-09-18 11:10:05 -07001212 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1213 mEventQueue->setEventConnection(
1214 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001216 }));
1217
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218 return NO_ERROR;
1219}
1220
1221status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001222 Mutex::Autolock lock(mStateLock);
1223 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001224}
1225
Lloyd Pique755e3192018-01-31 16:46:15 -08001226status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1227 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001228 // Try to acquire a lock for 1s, fail gracefully
1229 const status_t err = mStateLock.timedLock(s2ns(1));
1230 const bool locked = (err == NO_ERROR);
1231 if (!locked) {
1232 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1233 return TIMED_OUT;
1234 }
1235
1236 outLayers->clear();
1237 mCurrentState.traverseInZOrder([&](Layer* layer) {
1238 outLayers->push_back(layer->getLayerDebugInfo());
1239 });
1240
1241 mStateLock.unlock();
1242 return NO_ERROR;
1243}
1244
Peiyong Linc6780972018-10-28 15:24:08 -07001245status_t SurfaceFlinger::getCompositionPreference(
1246 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1247 Dataspace* outWideColorGamutDataspace,
1248 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001249 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001250 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001251 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001252 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001253 return NO_ERROR;
1254}
1255
Dan Stozaec460082018-12-17 15:35:09 -08001256status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1257 const sp<IBinder>& stopLayerHandle,
1258 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001259 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001260 return BAD_VALUE;
1261 }
1262 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001263 return NO_ERROR;
1264}
1265
Dan Stozaec460082018-12-17 15:35:09 -08001266status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001267 if (!listener) {
1268 return BAD_VALUE;
1269 }
Dan Stozaec460082018-12-17 15:35:09 -08001270 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001271 return NO_ERROR;
1272}
Dan Gittik57e63c52019-01-18 16:37:54 +00001273
1274status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1275 bool* outSupport) const {
1276 if (!displayToken || !outSupport) {
1277 return BAD_VALUE;
1278 }
1279 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1280 if (!displayId) {
1281 return NAME_NOT_FOUND;
1282 }
1283 *outSupport =
1284 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1285 return NO_ERROR;
1286}
1287
1288status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1289 float brightness) const {
1290 if (!displayToken) {
1291 return BAD_VALUE;
1292 }
1293 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1294 if (!displayId) {
1295 return NAME_NOT_FOUND;
1296 }
1297 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1298}
1299
Ady Abraham8532d012019-05-08 14:50:56 -07001300status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1301 PowerHint powerHint = static_cast<PowerHint>(hintId);
1302
1303 if (powerHint == PowerHint::INTERACTION) {
1304 mScheduler->notifyTouchEvent();
1305 }
1306
1307 return NO_ERROR;
1308}
1309
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001310// ----------------------------------------------------------------------------
1311
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001312sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001313 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001314 const auto& handle =
1315 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001316
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001317 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001318}
1319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001320// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001321
1322void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001323 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324}
1325
1326void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001327 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001328 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001329}
1330
1331void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001332 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001333 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001334}
1335
1336void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001337 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001338 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001339}
1340
1341status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001342 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001343 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001344}
1345
1346status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001347 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001348 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349 if (res == NO_ERROR) {
1350 msg->wait();
1351 }
1352 return res;
1353}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001355void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001356 do {
1357 waitForEvent();
1358 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001359}
1360
Dominik Laskowski83b88212018-12-11 13:34:06 -08001361nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001362 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001363 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1364 return 0;
1365 }
1366
1367 const auto config = getHwComposer().getActiveConfig(*displayId);
1368 return config ? config->getVsyncPeriod() : 0;
1369}
1370
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001371void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1372 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001373 ATRACE_NAME("SF onVsync");
1374
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
1379 }
1380
Dominik Laskowski075d3172018-05-24 15:50:06 -07001381 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001382 return;
1383 }
1384
Dominik Laskowski075d3172018-05-24 15:50:06 -07001385 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001386 // For now, we don't do anything with external display vsyncs.
1387 return;
1388 }
1389
Alec Mourif8e689c2019-05-20 18:32:22 -07001390 bool periodFlushed = false;
1391 mScheduler->addResyncSample(timestamp, &periodFlushed);
1392 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001393 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001394 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001395}
1396
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001398 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1399 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001400}
1401
Ady Abraham261614e2019-07-10 17:53:12 -07001402bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001403 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001404}
1405
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001406void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001407 const auto display = getDefaultDisplayDeviceLocked();
1408 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001409 return;
1410 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001411 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001412
Ana Krulec7d1d6832018-12-27 11:10:09 -08001413 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001414 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1415 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001416
Dominik Laskowski22488f62019-03-28 09:53:04 -07001417 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001418 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1419 return;
1420 }
1421
Dominik Laskowski22488f62019-03-28 09:53:04 -07001422 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001423}
1424
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001425void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001426 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001427 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001428 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
Lloyd Piqueba04e622017-12-14 17:11:26 -08001430 // Ignore events that do not have the right sequenceId.
1431 if (sequenceId != getBE().mComposerSequenceId) {
1432 return;
1433 }
1434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 // Only lock if we're not on the main thread. This function is normally
1436 // called on a hwbinder thread, but for the primary display it's called on
1437 // the main thread with the state lock already held, so don't attempt to
1438 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001439 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001440
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001441 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001442
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001443 if (std::this_thread::get_id() == mMainThreadId) {
1444 // Process all pending hot plug events immediately if we are on the main thread.
1445 processDisplayHotplugEventsLocked();
1446 }
1447
Lloyd Piqueba04e622017-12-14 17:11:26 -08001448 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001449}
1450
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001451void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001452 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001453 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001455 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001457}
1458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001459void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001460 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001461
1462 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1463 // display power state.
1464 postMessageAsync(new LambdaMessage(
1465 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1466}
1467
1468void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1469 ATRACE_CALL();
1470
Ady Abraham27c70212019-06-11 10:52:26 -07001471 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001473 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001474 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1475 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001476 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001478 }
Mathias Agopian86303202012-07-24 22:46:10 -07001479}
1480
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001482void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001483 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001484 // Clear the drawing state so that the logic inside of
1485 // handleTransactionLocked will fire. It will determine the delta between
1486 // mCurrentState and mDrawingState and re-apply all changes when we make the
1487 // transition.
1488 mDrawingState.displays.clear();
1489 mDisplays.clear();
1490}
1491
Steven Thomas050b2c82017-03-06 11:45:16 -08001492void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001493 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001494 if (!mVrFlinger)
1495 return;
1496 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001497 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001498 return;
1499 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001500
Lloyd Pique441d5042018-10-18 16:49:51 -07001501 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001502 ALOGE("Vr flinger is only supported for remote hardware composer"
1503 " service connections. Ignoring request to transition to vr"
1504 " flinger.");
1505 mVrFlingerRequestsDisplay = false;
1506 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001507 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001508
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001509 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001510
Steven Thomas0123ac62018-07-12 11:32:34 -07001511 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001512 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001513
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001514 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001515
1516 // Clear out all the output layers from the composition engine for all
1517 // displays before destroying the hardware composer interface. This ensures
1518 // any HWC layers are destroyed through that interface before it becomes
1519 // invalid.
1520 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001521 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001522 }
1523
Steven Thomas0123ac62018-07-12 11:32:34 -07001524 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1525 // called below. Clear the reference now so we don't accidentally use it
1526 // later.
1527 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001532
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001534 // Delete the current instance before creating the new one
1535 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1536 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1537 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1538 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539
Lloyd Pique441d5042018-10-18 16:49:51 -07001540 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001541 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001542
1543 if (vrFlingerRequestsDisplay) {
1544 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546
1547 mVisibleRegionsDirty = true;
1548 invalidateHwcGeometry();
1549
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001550 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001551 display = getDefaultDisplayDeviceLocked();
1552 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001553 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001554
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001556 const nsecs_t vsyncPeriod = getVsyncPeriod();
1557 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001558
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001559 // The present fences returned from vr_hwc are not an accurate
1560 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001561 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001562
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 // Use phase of 0 since phase is not known.
1564 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001565 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001566 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001567
Ana Krulecc2870422019-01-29 19:00:58 -08001568 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001569
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001570 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001571 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001572}
1573
Ady Abraham11579302019-09-19 12:35:58 -07001574bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1575 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001576 // We are storing the last 2 present fences. If sf's phase offset is to be
1577 // woken up before the actual vsync but targeting the next vsync, we need to check
1578 // fence N-2
1579 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001580 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001581 ? mPreviousPresentFences[0]
1582 : mPreviousPresentFences[1];
1583
Ady Abraham11579302019-09-19 12:35:58 -07001584 if (fence == Fence::NO_FENCE) {
1585 return false;
1586 }
1587
1588 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1589 fence->wait(graceTimeMs);
1590 }
1591
1592 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001593}
1594
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001595void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001596 DisplayStatInfo stats;
1597 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001598 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001599 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001600 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001601 mPhaseOffsets->getOffsetThresholdForNextVsync()
1602 ? presentTime
1603 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001604}
1605
Dominik Laskowski22488f62019-03-28 09:53:04 -07001606void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001607 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001608 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001609 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001610 // calculate the expected present time once and use the cached
1611 // value throughout this frame to make sure all layers are
1612 // seeing this same value.
1613 populateExpectedPresentTime();
1614
Ady Abraham11579302019-09-19 12:35:58 -07001615 // When Backpressure propagation is enabled we want to give a small grace period
1616 // for the present fence to fire instead of just giving up on this frame to handle cases
1617 // where present fence is just about to get signaled.
1618 const int graceTimeForPresentFenceMs =
1619 (mPropagateBackpressure &&
1620 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1621 ? 1
1622 : 0;
1623 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1624 previousFrameMissed(
1625 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001626 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1627 mHadDeviceComposition && frameMissed};
1628 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1629 mHadClientComposition && frameMissed};
1630
Alec Mouricc0fc602019-02-26 21:45:19 -08001631 if (frameMissed) {
1632 mFrameMissedCount++;
1633 mTimeStats->incrementMissedFrames();
1634 }
1635
Alec Mouri40189b02019-03-05 15:07:54 -08001636 if (hwcFrameMissed) {
1637 mHwcFrameMissedCount++;
1638 }
1639
1640 if (gpuFrameMissed) {
1641 mGpuFrameMissedCount++;
1642 }
1643
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001644 if (mUseSmart90ForVideo) {
1645 // This call is made each time SF wakes up and creates a new frame. It is part
1646 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001647 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001648 }
1649
Ady Abrahamb838aed2019-02-12 15:30:16 -08001650 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001651 break;
1652 }
1653
Ady Abrahamadb9a992019-09-19 21:21:55 +00001654 if (frameMissed && mPropagateBackpressure) {
1655 if ((hwcFrameMissed && !gpuFrameMissed) ||
1656 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001657 signalLayerUpdate();
1658 break;
1659 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001660 }
Dan Stoza50182882016-07-08 12:02:20 -07001661
Steven Thomas050b2c82017-03-06 11:45:16 -08001662 // Now that we're going to make it to the handleMessageTransaction()
1663 // call below it's safe to call updateVrFlinger(), which will
1664 // potentially trigger a display handoff.
1665 updateVrFlinger();
1666
Dan Stoza6b9454d2014-11-07 16:00:59 -08001667 bool refreshNeeded = handleMessageTransaction();
1668 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001669
1670 updateCursorAsync();
1671 updateInputFlinger();
1672
Dan Stoza58784442014-12-02 16:58:17 -08001673 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001674 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001675 // Signal a refresh if a transaction modified the window state,
1676 // a new buffer was latched, or if HWC has requested a full
1677 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001678 signalRefresh();
1679 }
1680 break;
1681 }
1682 case MessageQueue::REFRESH: {
1683 handleMessageRefresh();
1684 break;
1685 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001686 }
1687}
1688
Dan Stoza6b9454d2014-11-07 16:00:59 -08001689bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001690 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001691 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001692
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001693 bool flushedATransaction = flushTransactionQueues();
1694
1695 bool runHandleTransaction = transactionFlags &&
1696 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1697
1698 if (runHandleTransaction) {
1699 handleTransaction(eTransactionMask);
1700 } else {
1701 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001702 }
1703
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001704 if (transactionFlushNeeded()) {
1705 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001706 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001707
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001708 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709}
1710
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001712 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001713
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001714 mRefreshPending = false;
1715
Lloyd Piqueab039b52019-02-13 14:22:42 -08001716 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001717 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001718 for (const auto& [_, display] : mDisplays) {
1719 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1720 }
1721 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1722 auto compositionLayer = layer->getCompositionLayer();
1723 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1724 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001725 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1726 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1727 auto compositionLayer = layer->getCompositionLayer();
1728 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1729 }
1730
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001731 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001732 refreshArgs.outputColorSetting = useColorManagement
1733 ? mDisplayColorSetting
1734 : compositionengine::OutputColorSetting::kUnmanaged;
1735 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1736 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001737
1738 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1739 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001740
1741 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1742 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1743 mDrawingState.colorMatrixChanged = false;
1744 }
1745
1746 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1747
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001748 if (mDebugRegion != 0) {
1749 refreshArgs.devOptFlashDirtyRegionsDelay =
1750 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1751 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001752
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001753 mGeometryInvalid = false;
1754
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001755 mCompositionEngine->present(refreshArgs);
1756
David Sodmanfa9b2af2017-12-24 13:28:59 -08001757 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001758 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001759
Lloyd Pique66d68602019-02-13 14:23:31 -08001760 mHadClientComposition =
1761 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1762 auto& displayDevice = tokenDisplayPair.second;
1763 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1764 });
1765 mHadDeviceComposition =
1766 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1767 auto& displayDevice = tokenDisplayPair.second;
1768 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1769 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001770
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001771 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001772
David Sodman7e4ae112018-02-09 15:02:28 -08001773 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001774 if (mVisibleRegionsDirty) {
1775 mVisibleRegionsDirty = false;
1776 if (mTracingEnabled) {
1777 mTracing.notify("visibleRegionsDirty");
1778 }
1779 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001780
1781 if (mCompositionEngine->needsAnotherUpdate()) {
1782 signalLayerUpdate();
1783 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001784}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001785
David Sodmanfa9b2af2017-12-24 13:28:59 -08001786
1787bool SurfaceFlinger::handleMessageInvalidate() {
1788 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001789 bool refreshNeeded = handlePageFlip();
1790
Vishnu Nair4351ad52019-02-11 14:13:02 -08001791 if (mVisibleRegionsDirty) {
1792 computeLayerBounds();
1793 }
1794
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001795 for (auto& layer : mLayersPendingRefresh) {
1796 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001797 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001798 invalidateLayerStack(layer, visibleReg);
1799 }
1800 mLayersPendingRefresh.clear();
1801 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001802}
1803
Ana Krulece588e312018-09-18 12:32:24 -07001804void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1805 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806 // Update queue of past composite+present times and determine the
1807 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001808 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001809 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001810 while (!getBE().mCompositePresentTimes.empty()) {
1811 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812 // Cached values should have been updated before calling this method,
1813 // which helps avoid duplicate syscalls.
1814 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1815 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1816 break;
1817 }
1818 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001819 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001820 }
1821
1822 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001823 while (getBE().mCompositePresentTimes.size() > 16) {
1824 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001825 }
1826
Ana Krulece588e312018-09-18 12:32:24 -07001827 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001828}
1829
Ana Krulece588e312018-09-18 12:32:24 -07001830void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1831 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832 // Integer division and modulo round toward 0 not -inf, so we need to
1833 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001834 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1835 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1836 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001837
Ana Krulec757f63a2019-01-25 10:46:18 -08001838 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001839 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001840 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001841 }
1842
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001843 // Snap the latency to a value that removes scheduling jitter from the
1844 // composition and present times, which often have >1ms of jitter.
1845 // Reducing jitter is important if an app attempts to extrapolate
1846 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001847 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001848 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001849 nsecs_t bias = stats.vsyncPeriod / 2;
1850 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1851 nsecs_t snappedCompositeToPresentLatency =
1852 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853
David Sodman99974d22017-11-28 12:04:33 -08001854 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001855 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1856 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001857 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001858}
1859
David Sodman2b406362017-12-15 13:33:47 -08001860void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001861{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 ATRACE_CALL();
1863 ALOGV("postComposition");
1864
Brian Anderson3546a3f2016-07-14 11:51:14 -07001865 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001866 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001867 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001868 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001869 }
1870
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001871 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001872 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001873
David Sodman73beded2017-11-15 11:56:06 -08001874 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001875 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001876 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001877 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001878 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1879 ->getRenderSurface()
1880 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001881 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001882 } else {
1883 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1884 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001885
David Sodman73beded2017-11-15 11:56:06 -08001886 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001887 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1888 mPreviousPresentFences[0] = displayDevice
1889 ? getHwComposer().getPresentFence(*displayDevice->getId())
1890 : Fence::NO_FENCE;
1891 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001892 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001893
Ana Krulece588e312018-09-18 12:32:24 -07001894 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001895 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896
Lloyd Piqueab039b52019-02-13 14:22:42 -08001897 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1898 // be sampled a little later than when we started doing work for this frame,
1899 // but that should be okay since updateCompositorTiming has snapping logic.
1900 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1901 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001902 CompositorTiming compositorTiming;
1903 {
David Sodman99974d22017-11-28 12:04:33 -08001904 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1905 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001906 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001907
Robert Carr2047fae2016-11-28 14:09:09 -08001908 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001909 bool frameLatched =
1910 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1911 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001912 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001913 recordBufferingStats(layer->getName().string(),
1914 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001915 }
Robert Carr2047fae2016-11-28 14:09:09 -08001916 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001917
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001918 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001919 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001920 }
1921
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001922 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001923 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1924 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001925 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001926 }
1927 }
1928
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001929 if (mAnimCompositionPending) {
1930 mAnimCompositionPending = false;
1931
Brian Anderson4e606e32017-03-16 15:34:57 -07001932 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001933 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001934 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001935 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001936 // The HWC doesn't support present fences, so use the refresh
1937 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001938 const nsecs_t presentTime =
1939 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001940 mAnimFrameTracker.setActualPresentTime(presentTime);
1941 }
1942 mAnimFrameTracker.advanceFrame();
1943 }
Dan Stozab90cf072015-03-05 11:05:59 -08001944
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001945 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001946 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001947 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001948 }
1949
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001950 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001951
Lloyd Pique32cbe282018-10-19 13:09:22 -07001952 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1953 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001954 return;
1955 }
1956
1957 nsecs_t currentTime = systemTime();
1958 if (mHasPoweredOff) {
1959 mHasPoweredOff = false;
1960 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001961 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001962 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001963 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1964 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001965 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001966 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001967 }
David Sodman4a36e932017-11-07 14:29:47 -08001968 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001969 }
David Sodman4a36e932017-11-07 14:29:47 -08001970 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001971
1972 {
1973 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001974 if (mTexturePool.size() < mTexturePoolSize) {
1975 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001976 const size_t offset = mTexturePool.size();
1977 mTexturePool.resize(mTexturePoolSize);
1978 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1979 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001980 } else if (mTexturePool.size() > mTexturePoolSize) {
1981 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1982 const size_t offset = mTexturePoolSize;
1983 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1984 mTexturePool.resize(mTexturePoolSize);
1985 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001986 }
1987 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001988
Ady Abrahambe0f9482019-04-24 15:41:53 -07001989 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001990 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001991
Kevin DuBois413287f2019-02-25 08:46:47 -08001992 if (mLumaSampling && mRegionSamplingThread) {
1993 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001994 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07001995
1996 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
1997 // side-effect of getTotalSize(), so we check that again here
1998 if (ATRACE_ENABLED()) {
1999 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2000 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001}
2002
Vishnu Nair4351ad52019-02-11 14:13:02 -08002003void SurfaceFlinger::computeLayerBounds() {
2004 for (const auto& pair : mDisplays) {
2005 const auto& displayDevice = pair.second;
2006 const auto display = displayDevice->getCompositionDisplay();
2007 for (const auto& layer : mDrawingState.layersSortedByZ) {
2008 // only consider the layers on the given layer stack
2009 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002010 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002011 }
2012
2013 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2014 }
2015 }
2016}
2017
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018void SurfaceFlinger::postFrame()
2019{
2020 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002021 const auto display = getDefaultDisplayDeviceLocked();
2022 if (display && getHwComposer().isConnected(*display->getId())) {
2023 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002024 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2025 logFrameStats();
2026 }
2027 }
2028}
2029
Mathias Agopian87baae12012-07-31 12:38:26 -07002030void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031{
Mathias Agopian841cde52012-03-01 15:44:37 -08002032 ATRACE_CALL();
2033
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002034 // here we keep a copy of the drawing state (that is the state that's
2035 // going to be overwritten by handleTransactionLocked()) outside of
2036 // mStateLock so that the side-effects of the State assignment
2037 // don't happen with mStateLock held (which can cause deadlocks).
2038 State drawingState(mDrawingState);
2039
Mathias Agopianca4d3602011-05-19 15:38:14 -07002040 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002041 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042
Mathias Agopianca4d3602011-05-19 15:38:14 -07002043 // Here we're guaranteed that some transaction flags are set
2044 // so we can call handleTransactionLocked() unconditionally.
2045 // We call getTransactionFlags(), which will also clear the flags,
2046 // with mStateLock held to guarantee that mCurrentState won't change
2047 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002048
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002049 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002050 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002051 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002052
Mathias Agopianca4d3602011-05-19 15:38:14 -07002053 mDebugInTransaction = 0;
2054 invalidateHwcGeometry();
2055 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002056}
2057
Lloyd Piqueba04e622017-12-14 17:11:26 -08002058void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2059 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002060 const std::optional<DisplayIdentificationInfo> info =
2061 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002062
Dominik Laskowski075d3172018-05-24 15:50:06 -07002063 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002064 continue;
2065 }
2066
Lloyd Piqueba04e622017-12-14 17:11:26 -08002067 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002068 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002069 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002070 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2071 initScheduler(info->id);
2072 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002073 mPhysicalDisplayTokens[info->id] = new BBinder();
2074 DisplayDeviceState state;
2075 state.displayId = info->id;
2076 state.isSecure = true; // All physical displays are currently considered secure.
2077 state.displayName = info->name;
2078 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2079 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002080 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002081 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002082 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002083
Dominik Laskowski075d3172018-05-24 15:50:06 -07002084 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2085 if (index >= 0) {
2086 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2087 mInterceptor->saveDisplayDeletion(state.sequenceId);
2088 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002089 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002090 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002091 }
2092
2093 processDisplayChangesLocked();
2094 }
2095
2096 mPendingHotplugEvents.clear();
2097}
2098
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002099void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002100 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2101 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002102}
2103
Lloyd Pique99d3da52018-01-22 17:48:03 -08002104sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002105 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002106 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002107 const sp<IGraphicBufferProducer>& producer) {
2108 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002109 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002110 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002111 creationArgs.isSecure = state.isSecure;
2112 creationArgs.displaySurface = dispSurface;
2113 creationArgs.hasWideColorGamut = false;
2114 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002115 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002116
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002117 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002118 creationArgs.isPrimary = isInternalDisplay;
2119
2120 if (useColorManagement && displayId) {
2121 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002122 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002123 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002124 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002125 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002126
Dominik Laskowski7e045462018-05-30 13:02:02 -07002127 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002128 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002129 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002130 }
tangrobin6753a022018-08-10 10:58:54 +08002131 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002132
Dominik Laskowski075d3172018-05-24 15:50:06 -07002133 if (displayId) {
2134 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002135 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002136 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002137 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002138
Lloyd Pique90c115d2018-09-18 21:39:42 -07002139 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002140 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002141 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002142
Lloyd Pique99d3da52018-01-22 17:48:03 -08002143 // Make sure that composition can never be stalled by a virtual display
2144 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002145 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002146 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002147 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2148 }
2149
Dominik Laskowski075d3172018-05-24 15:50:06 -07002150 creationArgs.displayInstallOrientation =
2151 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002152
Lloyd Pique99d3da52018-01-22 17:48:03 -08002153 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002154 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002155
Lloyd Pique90c115d2018-09-18 21:39:42 -07002156 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002157
2158 if (maxFrameBufferAcquiredBuffers >= 3) {
2159 nativeWindowSurface->preallocateBuffers();
2160 }
2161
2162 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002163 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002164 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002165 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002166 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002167 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002168 display->getCompositionDisplay()->setColorProfile(
2169 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2170 RenderIntent::COLORIMETRIC,
2171 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002172 if (!state.isVirtual()) {
2173 LOG_ALWAYS_FATAL_IF(!displayId);
2174 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002175 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002177 display->setLayerStack(state.layerStack);
2178 display->setProjection(state.orientation, state.viewport, state.frame);
2179 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002181 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002182}
2183
Lloyd Pique347200f2017-12-14 17:00:15 -08002184void SurfaceFlinger::processDisplayChangesLocked() {
2185 // here we take advantage of Vector's copy-on-write semantics to
2186 // improve performance by skipping the transaction entirely when
2187 // know that the lists are identical
2188 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2189 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2190 if (!curr.isIdenticalTo(draw)) {
2191 mVisibleRegionsDirty = true;
2192 const size_t cc = curr.size();
2193 size_t dc = draw.size();
2194
2195 // find the displays that were removed
2196 // (ie: in drawing state but not in current state)
2197 // also handle displays that changed
2198 // (ie: displays that are in both lists)
2199 for (size_t i = 0; i < dc;) {
2200 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2201 if (j < 0) {
2202 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002204 // Save display ID before disconnecting.
2205 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002206 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002207
2208 if (!display->isVirtual()) {
2209 LOG_ALWAYS_FATAL_IF(!displayId);
2210 dispatchDisplayHotplugEvent(displayId->value, false);
2211 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002213
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002214 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002215 } else {
2216 // this display is in both lists. see if something changed.
2217 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002218 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002219 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2220 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2221 if (state_binder != draw_binder) {
2222 // changing the surface is like destroying and
2223 // recreating the DisplayDevice, so we just remove it
2224 // from the drawing state, so that it get re-added
2225 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002227 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002228 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002229 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002230 mDrawingState.displays.removeItemsAt(i);
2231 dc--;
2232 // at this point we must loop to the next item
2233 continue;
2234 }
2235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002236 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002237 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002238 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002239 }
2240 if ((state.orientation != draw[i].orientation) ||
2241 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002242 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002243 }
2244 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002246 }
2247 }
2248 }
2249 ++i;
2250 }
2251
2252 // find displays that were added
2253 // (ie: in current state but not in drawing state)
2254 for (size_t i = 0; i < cc; i++) {
2255 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2256 const DisplayDeviceState& state(curr[i]);
2257
Lloyd Pique542307f2018-10-19 13:24:08 -07002258 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002259 sp<IGraphicBufferProducer> producer;
2260 sp<IGraphicBufferProducer> bqProducer;
2261 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002262 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002263
Dominik Laskowski075d3172018-05-24 15:50:06 -07002264 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002265 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002266 // Virtual displays without a surface are dormant:
2267 // they have external state (layer stack, projection,
2268 // etc.) but no internal state (i.e. a DisplayDevice).
2269 if (state.surface != nullptr) {
2270 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002271 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002272 int width = 0;
2273 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2274 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2275 int height = 0;
2276 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2277 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2278 int intFormat = 0;
2279 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2280 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002281 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002282
Dominik Laskowski075d3172018-05-24 15:50:06 -07002283 displayId =
2284 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002285 }
2286
2287 // TODO: Plumb requested format back up to consumer
2288
2289 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002290 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002291 bqProducer, bqConsumer,
2292 state.displayName);
2293
2294 dispSurface = vds;
2295 producer = vds;
2296 }
2297 } else {
2298 ALOGE_IF(state.surface != nullptr,
2299 "adding a supported display, but rendering "
2300 "surface is provided (%p), ignoring it",
2301 state.surface.get());
2302
Dominik Laskowski075d3172018-05-24 15:50:06 -07002303 displayId = state.displayId;
2304 LOG_ALWAYS_FATAL_IF(!displayId);
2305 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002306 producer = bqProducer;
2307 }
2308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002310 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002311 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002312 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002313 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002314 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002315 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002316 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002317 }
2318 }
2319 }
2320 }
2321 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002322
2323 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002324}
2325
Mathias Agopian87baae12012-07-31 12:38:26 -07002326void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002327{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002328 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2329
Dan Stoza7dde5992015-05-22 09:51:44 -07002330 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002331 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2332 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002333 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 /*
2336 * Traversal of the children
2337 * (perform the transaction for each of them if needed)
2338 */
2339
Marissa Wall06255332019-03-27 13:48:27 -07002340 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002341 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002343 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344
2345 const uint32_t flags = layer->doTransaction(0);
2346 if (flags & Layer::eVisibleRegion)
2347 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002348
2349 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002350 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002351 }
Robert Carr2047fae2016-11-28 14:09:09 -08002352 });
Marissa Wall06255332019-03-27 13:48:27 -07002353 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354 }
2355
2356 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002357 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358 */
2359
Mathias Agopiane57f2922012-08-09 16:29:12 -07002360 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002361 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002362 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002363 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002365 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002366 // The transform hint might have changed for some layers
2367 // (either because a display has changed, or because a layer
2368 // as changed).
2369 //
2370 // Walk through all the layers in currentLayers,
2371 // and update their transform hint.
2372 //
2373 // If a layer is visible only on a single display, then that
2374 // display is used to calculate the hint, otherwise we use the
2375 // default display.
2376 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002377 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002378 // the hint is set before we acquire a buffer from the surface texture.
2379 //
2380 // NOTE: layer transactions have taken place already, so we use their
2381 // drawing state. However, SurfaceFlinger's own transaction has not
2382 // happened yet, so we must use the current state layer list
2383 // (soon to become the drawing state list).
2384 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002385 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002386 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002387 bool first = true;
2388 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002389 // NOTE: we rely on the fact that layers are sorted by
2390 // layerStack first (so we don't have to traverse the list
2391 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002392 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002393 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002394 currentlayerStack = layerStack;
2395 // figure out if this layerstack is mirrored
2396 // (more than one display) if so, pick the default display,
2397 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002398 hintDisplay = nullptr;
2399 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002400 if (display->getCompositionDisplay()
2401 ->belongsInOutput(layer->getLayerStack(),
2402 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002403 if (hintDisplay) {
2404 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002405 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002407 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002408 }
2409 }
2410 }
2411 }
Chet Haase91d25932013-04-11 15:24:55 -07002412
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002413 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002414 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2415 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002416
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002417 // could be null when this layer is using a layerStack
2418 // that is not visible on any display. Also can occur at
2419 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002420 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002421 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002422
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002423 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002424 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002425 if (hintDisplay) {
2426 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002427 }
Robert Carr2047fae2016-11-28 14:09:09 -08002428
2429 first = false;
2430 });
Mathias Agopian84300952012-11-21 16:02:13 -08002431 }
2432
2433
Mathias Agopian3559b072012-08-15 13:46:03 -07002434 /*
2435 * Perform our own transaction if needed
2436 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002437
2438 if (mLayersAdded) {
2439 mLayersAdded = false;
2440 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002441 mVisibleRegionsDirty = true;
2442 }
2443
2444 // some layers might have been removed, so
2445 // we need to update the regions they're exposing.
2446 if (mLayersRemoved) {
2447 mLayersRemoved = false;
2448 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002449 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002450 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002451 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002453 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002454 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002455 }
Robert Carr2047fae2016-11-28 14:09:09 -08002456 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 }
2458
Vishnu Nairec0ab382019-02-13 15:32:56 -08002459 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002461}
2462
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002463void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002464 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002465 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002466 return;
2467 }
2468
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002469 if (mVisibleRegionsDirty || mInputInfoChanged) {
2470 mInputInfoChanged = false;
2471 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002472 } else if (mInputWindowCommands.syncInputWindows) {
2473 // If the caller requested to sync input windows, but there are no
2474 // changes to input windows, notify immediately.
2475 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002476 }
2477
Arthur Hung6cbb9752019-09-05 16:38:18 +08002478 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002479}
2480
2481void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002482 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002483
2484 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2485 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002486 // When calculating the screen bounds we ignore the transparent region since it may
2487 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002488 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002489 }
2490 });
chaviw291d88a2019-02-14 10:33:58 -08002491
2492 mInputFlinger->setInputWindows(inputHandles,
2493 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2494 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002495}
2496
Vishnu Nairec0ab382019-02-13 15:32:56 -08002497void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002498 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002499 mPendingInputWindowCommands.clear();
2500}
2501
Riley Andrews03414a12014-07-01 14:22:59 -07002502void SurfaceFlinger::updateCursorAsync()
2503{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002504 compositionengine::CompositionRefreshArgs refreshArgs;
2505 for (const auto& [_, display] : mDisplays) {
2506 if (display->getId()) {
2507 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002508 }
2509 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002510
2511 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002512}
2513
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002514void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2515 if (mScheduler) {
2516 // In practice it's not allowed to hotplug in/out the primary display once it's been
2517 // connected during startup, but some tests do it, so just warn and return.
2518 ALOGW("Can't re-init scheduler");
2519 return;
2520 }
2521
2522 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2523 mRefreshRateConfigs =
2524 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2525 getHwComposer().getConfigs(
2526 primaryDisplayId),
2527 currentConfig);
2528 mRefreshRateStats =
2529 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2530 currentConfig, HWC_POWER_MODE_OFF);
2531 mRefreshRateStats->setConfigMode(currentConfig);
2532
2533 // start the EventThread
2534 mScheduler =
2535 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2536 *mRefreshRateConfigs);
2537 mAppConnectionHandle =
2538 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2539 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2540 impl::EventThread::InterceptVSyncsCallback());
2541 mSfConnectionHandle =
2542 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2543 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2544 [this](nsecs_t timestamp) {
2545 mInterceptor->saveVSyncEvent(timestamp);
2546 });
2547
2548 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2549 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2550 mPhaseOffsets->getCurrentOffsets());
2551
2552 mRegionSamplingThread =
2553 new RegionSamplingThread(*this, *mScheduler,
2554 RegionSamplingThread::EnvironmentTimingTunables());
2555
2556 mScheduler->setChangeRefreshRateCallback(
2557 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2558 Mutex::Autolock lock(mStateLock);
2559 setRefreshRateTo(type, event);
2560 });
2561}
2562
Mathias Agopian4fec8732012-06-29 14:12:52 -07002563void SurfaceFlinger::commitTransaction()
2564{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002565 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002566
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002567 mTransactionPending = false;
2568 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570}
2571
Lloyd Pique58e24a32019-08-01 15:50:14 -07002572void SurfaceFlinger::commitTransactionLocked() {
2573 if (!mLayersPendingRemoval.isEmpty()) {
2574 // Notify removed layers now that they can't be drawn from
2575 for (const auto& l : mLayersPendingRemoval) {
2576 recordBufferingStats(l->getName().string(), l->getOccupancyHistory(true));
2577
2578 // Ensure any buffers set to display on any children are released.
2579 if (l->isRemovedFromCurrentState()) {
2580 l->latchAndReleaseBuffer();
2581 }
2582
2583 // If the layer has been removed and has no parent, then it will not be reachable
2584 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2585 // ensure we can copy its current to drawing state.
2586 if (!l->getParent()) {
2587 mOffscreenLayers.emplace(l.get());
2588 }
2589 }
2590 mLayersPendingRemoval.clear();
2591 }
2592
2593 // If this transaction is part of a window animation then the next frame
2594 // we composite should be considered an animation as well.
2595 mAnimCompositionPending = mAnimTransactionPending;
2596
2597 mDrawingState = mCurrentState;
2598 // clear the "changed" flags in current state
2599 mCurrentState.colorMatrixChanged = false;
2600
2601 mDrawingState.traverseInZOrder([&](Layer* layer) {
2602 layer->commitChildList();
2603
2604 // If the layer can be reached when traversing mDrawingState, then the layer is no
2605 // longer offscreen. Remove the layer from the offscreenLayer set.
2606 if (mOffscreenLayers.count(layer)) {
2607 mOffscreenLayers.erase(layer);
2608 }
2609 });
2610
2611 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002612 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002613}
2614
Nataniel Borges2b796da2019-02-15 13:32:18 -08002615void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2616 if (mTracingEnabledChanged) {
2617 mTracingEnabled = mTracing.isEnabled();
2618 mTracingEnabledChanged = false;
2619 }
2620
2621 // Synchronize with Tracing thread
2622 std::unique_lock<std::mutex> lock;
2623 if (mTracingEnabled) {
2624 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2625 }
2626
2627 lockedOperation();
2628
2629 // Synchronize with Tracing thread
2630 if (mTracingEnabled) {
2631 lock.unlock();
2632 }
2633}
2634
chaviw74d90ad2019-04-26 14:45:26 -07002635void SurfaceFlinger::commitOffscreenLayers() {
2636 for (Layer* offscreenLayer : mOffscreenLayers) {
2637 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2638 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2639 if (!trFlags) return;
2640
2641 layer->doTransaction(0);
2642 layer->commitChildList();
2643 });
2644 }
2645}
2646
Chia-I Wuab0c3192017-08-01 11:29:00 -07002647void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002648 for (const auto& [token, displayDevice] : mDisplays) {
2649 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002650 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002651 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002652 }
2653 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002654}
2655
Dan Stoza6b9454d2014-11-07 16:00:59 -08002656bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657{
Ady Abraham09bd3922019-04-08 10:44:56 -07002658 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 ALOGV("handlePageFlip");
2660
Brian Andersond6927fb2016-07-23 23:37:30 -07002661 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Mathias Agopian4fec8732012-06-29 14:12:52 -07002663 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002664 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002665 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002666
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002667 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2668
Eric Penner51c59cd2014-07-28 19:51:58 -07002669 // Store the set of layers that need updates. This set must not change as
2670 // buffers are being latched, as this could result in a deadlock.
2671 // Example: Two producers share the same command stream and:
2672 // 1.) Layer 0 is latched
2673 // 2.) Layer 0 gets a new frame
2674 // 2.) Layer 1 gets a new frame
2675 // 3.) Layer 1 is latched.
2676 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2677 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002678 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002679 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002680 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002681 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002682 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002683 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002684 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002685 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002686 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002687 } else {
2688 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002689 }
Robert Carr2047fae2016-11-28 14:09:09 -08002690 });
2691
chaviw49a108c2019-08-12 11:23:06 -07002692 // The client can continue submitting buffers for offscreen layers, but they will not
2693 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2694 // layers to ensure dequeueBuffer doesn't block indefinitely.
2695 for (Layer* offscreenLayer : mOffscreenLayers) {
2696 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2697 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2698 }
2699
Lloyd Piquef2c79392018-12-20 16:23:33 -08002700 if (!mLayersWithQueuedFrames.empty()) {
2701 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2702 // writes to Layer current state. See also b/119481871
2703 Mutex::Autolock lock(mStateLock);
2704
2705 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002706 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002707 mLayersPendingRefresh.push_back(layer);
2708 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002709 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002710 if (layer->isBufferLatched()) {
2711 newDataLatched = true;
2712 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002713 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002715
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002716 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002717
2718 // If we will need to wake up at some time in the future to deal with a
2719 // queued frame that shouldn't be displayed during this vsync period, wake
2720 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002721 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002722 signalLayerUpdate();
2723 }
2724
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002725 // enter boot animation on first buffer latch
2726 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2727 ALOGI("Enter boot animation");
2728 mBootStage = BootStage::BOOTANIMATION;
2729 }
2730
chaviw74b03172019-08-19 11:09:03 -07002731 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2732
Dan Stoza6b9454d2014-11-07 16:00:59 -08002733 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002734 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735}
2736
Mathias Agopianad456f92011-01-13 17:53:01 -08002737void SurfaceFlinger::invalidateHwcGeometry()
2738{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002740}
2741
Robert Carrc0df3122019-04-11 13:18:21 -07002742status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2743 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2744 const sp<IBinder>& parentHandle,
2745 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002746 // add this layer to the current state list
2747 {
2748 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002749 sp<Layer> parent;
2750 if (parentHandle != nullptr) {
2751 parent = fromHandle(parentHandle);
2752 if (parent == nullptr) {
2753 return NAME_NOT_FOUND;
2754 }
2755 } else {
2756 parent = parentLayer;
2757 }
2758
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002760 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002761 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002762 return NO_MEMORY;
2763 }
Robert Carrc0df3122019-04-11 13:18:21 -07002764
2765 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2766
Robert Carrb89ea9d2018-12-10 13:01:14 -08002767 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002769 } else if (parent == nullptr) {
2770 lbc->onRemovedFromCurrentState();
2771 } else if (parent->isRemovedFromCurrentState()) {
2772 parent->addChild(lbc);
2773 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002774 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 parent->addChild(lbc);
2776 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002777
Yiwei Zhang243b3782018-05-15 17:40:04 -07002778 if (gbc != nullptr) {
2779 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2780 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2781 mMaxGraphicBufferProducerListSize,
2782 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2783 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002784 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002785 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002787 }
2788
Mathias Agopian96f08192010-06-02 23:28:45 -07002789 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002790 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002791
Dan Stoza7d89d062015-04-30 13:29:25 -07002792 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002793}
2794
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002795uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002796 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002797}
2798
Mathias Agopian3f844832013-08-07 21:24:32 -07002799uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002800 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801}
2802
Mathias Agopian3f844832013-08-07 21:24:32 -07002803uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002804 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002805}
2806
2807uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002808 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002809 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002810 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002812 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 }
2814 return old;
2815}
2816
Marissa Wall713b63f2018-10-17 15:42:43 -07002817bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002818 // to prevent onHandleDestroyed from being called while the lock is held,
2819 // we must keep a copy of the transactions (specifically the composer
2820 // states) around outside the scope of the lock
2821 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002822 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002823 {
2824 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002825
Valerie Haufce31b82019-04-30 16:41:14 -07002826 auto it = mTransactionQueues.begin();
2827 while (it != mTransactionQueues.end()) {
2828 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002829
Valerie Haufce31b82019-04-30 16:41:14 -07002830 while (!transactionQueue.empty()) {
2831 const auto& transaction = transactionQueue.front();
2832 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002833 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002834 transaction.states)) {
2835 setTransactionFlags(eTransactionFlushNeeded);
2836 break;
2837 }
2838 transactions.push_back(transaction);
2839 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2840 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002841 transaction.buffer, transaction.postTime,
2842 transaction.privileged, transaction.hasListenerCallbacks,
2843 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002844 transactionQueue.pop();
2845 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002846 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002847
Valerie Haufce31b82019-04-30 16:41:14 -07002848 if (transactionQueue.empty()) {
2849 it = mTransactionQueues.erase(it);
2850 mTransactionCV.broadcast();
2851 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002852 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002853 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002854 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002855 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002856 return flushedATransaction;
2857}
2858
2859bool SurfaceFlinger::transactionFlushNeeded() {
2860 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002861}
2862
chaviwca27f252018-02-06 16:46:39 -08002863
Marissa Wall17b4e452018-12-26 16:32:34 -08002864bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002865 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002866 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002867 if (!useCachedExpectedPresentTime)
2868 populateExpectedPresentTime();
2869
2870 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002871 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2872 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2873 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2874 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2875 return false;
2876 }
2877
Marissa Wall713b63f2018-10-17 15:42:43 -07002878 for (const ComposerState& state : states) {
2879 const layer_state_t& s = state.state;
2880 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2881 continue;
2882 }
2883 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002884 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002885 }
2886 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002887 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002888}
2889
Valerie Hau9dab9732019-08-20 09:29:25 -07002890void SurfaceFlinger::setTransactionState(
2891 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2892 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2893 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2894 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002895 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002896
Valerie Haubc6ddb12019-03-08 11:10:15 -08002897 const int64_t postTime = systemTime();
2898
Robert Carr14167e02019-02-13 13:50:55 -08002899 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2900
Mathias Agopian698c0872011-06-28 19:09:31 -07002901 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002902
Marissa Wall713b63f2018-10-17 15:42:43 -07002903 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002904 auto itr = mTransactionQueues.find(applyToken);
2905 // if this is an animation frame, wait until prior animation frame has
2906 // been applied by SF
2907 if (flags & eAnimation) {
2908 while (itr != mTransactionQueues.end()) {
2909 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2910 if (CC_UNLIKELY(err != NO_ERROR)) {
2911 ALOGW_IF(err == TIMED_OUT,
2912 "setTransactionState timed out "
2913 "waiting for animation frame to apply");
2914 break;
2915 }
2916 itr = mTransactionQueues.find(applyToken);
2917 }
2918 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002919
2920 // Expected present time is computed and cached on invalidate, so it may be stale.
2921 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2922 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002923 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002924 uncacheBuffer, postTime, privileged,
2925 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002926 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002927 return;
2928 }
2929
Valerie Haubc6ddb12019-03-08 11:10:15 -08002930 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002931 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2932 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002933}
2934
Valerie Hau9dab9732019-08-20 09:29:25 -07002935void SurfaceFlinger::applyTransactionState(
2936 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2937 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2938 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2939 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2940 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002941 uint32_t transactionFlags = 0;
2942
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002943 if (flags & eAnimation) {
2944 // For window updates that are part of an animation we must wait for
2945 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002946 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002947 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002948 if (CC_UNLIKELY(err != NO_ERROR)) {
2949 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002950 // caller after a few seconds.
2951 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2952 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002953 mAnimTransactionPending = false;
2954 break;
2955 }
2956 }
2957 }
2958
chaviwca27f252018-02-06 16:46:39 -08002959 for (const DisplayState& display : displays) {
2960 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002961 }
2962
Valerie Hau9dab9732019-08-20 09:29:25 -07002963 // start and end registration for listeners w/ no surface so they can get their callback. Note
2964 // that listeners with SurfaceControls will start registration during setClientStateLocked
2965 // below.
2966 for (const auto& listener : listenerCallbacks) {
2967 mTransactionCompletedThread.startRegistration(listener);
2968 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002969 }
2970
Valerie Hau9dab9732019-08-20 09:29:25 -07002971 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002972 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002973 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002974 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2975 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002976 }
2977
Valerie Hau9dab9732019-08-20 09:29:25 -07002978 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002979 mTransactionCompletedThread.endRegistration(listenerCallback);
2980 }
2981
Marissa Walle2ffb422018-10-12 11:33:52 -07002982 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002983 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002984 mTransactionCompletedThread.sendCallbacks();
2985 }
2986 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002987
chaviw273171b2018-12-26 11:46:30 -08002988 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2989
Marissa Wall947d34e2019-03-29 14:03:53 -07002990 if (uncacheBuffer.isValid()) {
2991 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002992 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002993 }
2994
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002995 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2996 // anyway. This can be used as a flush mechanism for previous async transactions.
2997 // Empty animation transaction can be used to simulate back-pressure, so also force a
2998 // transaction for empty animation transactions.
2999 if (transactionFlags == 0 &&
3000 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003001 transactionFlags = eTransactionNeeded;
3002 }
3003
Marissa Wall06255332019-03-27 13:48:27 -07003004 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3005 // so we don't have to wake up again next frame to preform an uneeded traversal.
3006 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3007 transactionFlags = transactionFlags & (~eTraversalNeeded);
3008 mTraversalNeededMainThread = true;
3009 }
3010
Mathias Agopian386aa982011-11-07 21:58:03 -08003011 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003012 if (mInterceptor->isEnabled()) {
3013 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003014 }
Irvel468051e2016-06-13 16:44:44 -07003015
Mathias Agopian386aa982011-11-07 21:58:03 -08003016 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003017 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3018 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003019 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003020
3021 // if this is a synchronous transaction, wait for it to take effect
3022 // before returning.
3023 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003024 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003025 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003026 if (flags & eAnimation) {
3027 mAnimTransactionPending = true;
3028 }
chaviw4fe36852019-04-15 16:25:49 -07003029 if (mPendingInputWindowCommands.syncInputWindows) {
3030 mPendingSyncInputWindows = true;
3031 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003032
3033 // applyTransactionState can be called by either the main SF thread or by
3034 // another process through setTransactionState. While a given process may wish
3035 // to wait on synchronous transactions, the main SF thread should never
3036 // be blocked. Therefore, we only wait if isMainThread is false.
3037 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003038 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3039 if (CC_UNLIKELY(err != NO_ERROR)) {
3040 // just in case something goes wrong in SF, return to the
3041 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003042 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3043 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003044 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003045 break;
3046 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003047 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048 }
3049}
3050
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003051uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3052 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3053 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003054
Mathias Agopiane57f2922012-08-09 16:29:12 -07003055 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003056 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3057
3058 const uint32_t what = s.what;
3059 if (what & DisplayState::eSurfaceChanged) {
3060 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3061 state.surface = s.surface;
3062 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003063 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003065 if (what & DisplayState::eLayerStackChanged) {
3066 if (state.layerStack != s.layerStack) {
3067 state.layerStack = s.layerStack;
3068 flags |= eDisplayTransactionNeeded;
3069 }
3070 }
3071 if (what & DisplayState::eDisplayProjectionChanged) {
3072 if (state.orientation != s.orientation) {
3073 state.orientation = s.orientation;
3074 flags |= eDisplayTransactionNeeded;
3075 }
3076 if (state.frame != s.frame) {
3077 state.frame = s.frame;
3078 flags |= eDisplayTransactionNeeded;
3079 }
3080 if (state.viewport != s.viewport) {
3081 state.viewport = s.viewport;
3082 flags |= eDisplayTransactionNeeded;
3083 }
3084 }
3085 if (what & DisplayState::eDisplaySizeChanged) {
3086 if (state.width != s.width) {
3087 state.width = s.width;
3088 flags |= eDisplayTransactionNeeded;
3089 }
3090 if (state.height != s.height) {
3091 state.height = s.height;
3092 flags |= eDisplayTransactionNeeded;
3093 }
3094 }
3095
Mathias Agopiane57f2922012-08-09 16:29:12 -07003096 return flags;
3097}
3098
Robert Carr14167e02019-02-13 13:50:55 -08003099bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003100 IPCThreadState* ipc = IPCThreadState::self();
3101 const int pid = ipc->getCallingPid();
3102 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003103 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003104 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003105 return false;
3106 }
3107 return true;
3108}
3109
Marissa Wall3dad52d2019-03-22 14:03:19 -07003110uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003111 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3112 bool privileged,
3113 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003114 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003115
Valerie Hau9dab9732019-08-20 09:29:25 -07003116 for (auto& listener : s.listeners) {
3117 // note that startRegistration will not re-register if the listener has
3118 // already be registered for a prior surface control
3119 mTransactionCompletedThread.startRegistration(listener);
3120 listenerCallbacks.insert(listener);
3121 }
3122
Vishnu Nairf03652d2019-07-16 17:56:56 -07003123 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003124 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003125 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003126 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003127 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003128 }
chaviw8b3871a2017-11-01 17:41:01 -07003129 return 0;
3130 }
3131
chaviw8b3871a2017-11-01 17:41:01 -07003132 uint32_t flags = 0;
3133
Garfield Tan8a3083e2018-12-03 13:21:07 -08003134 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003135
3136 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3137 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003138 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003139 layer->pushPendingState();
3140 }
3141
chaviw8b3871a2017-11-01 17:41:01 -07003142 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003143 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003144 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003145 }
chaviw8b3871a2017-11-01 17:41:01 -07003146 }
3147 if (what & layer_state_t::eLayerChanged) {
3148 // NOTE: index needs to be calculated before we update the state
3149 const auto& p = layer->getParent();
3150 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003151 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003152 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003153 mCurrentState.layersSortedByZ.removeAt(idx);
3154 mCurrentState.layersSortedByZ.add(layer);
3155 // we need traversal (state changed)
3156 // AND transaction (list changed)
3157 flags |= eTransactionNeeded|eTraversalNeeded;
3158 }
chaviw8b3871a2017-11-01 17:41:01 -07003159 } else {
3160 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003161 flags |= eTransactionNeeded|eTraversalNeeded;
3162 }
3163 }
chaviw8b3871a2017-11-01 17:41:01 -07003164 }
3165 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003166 // NOTE: index needs to be calculated before we update the state
3167 const auto& p = layer->getParent();
3168 if (p == nullptr) {
3169 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3170 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3171 mCurrentState.layersSortedByZ.removeAt(idx);
3172 mCurrentState.layersSortedByZ.add(layer);
3173 // we need traversal (state changed)
3174 // AND transaction (list changed)
3175 flags |= eTransactionNeeded|eTraversalNeeded;
3176 }
3177 } else {
3178 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3179 flags |= eTransactionNeeded|eTraversalNeeded;
3180 }
chaviw8b3871a2017-11-01 17:41:01 -07003181 }
3182 }
3183 if (what & layer_state_t::eSizeChanged) {
3184 if (layer->setSize(s.w, s.h)) {
3185 flags |= eTraversalNeeded;
3186 }
3187 }
3188 if (what & layer_state_t::eAlphaChanged) {
3189 if (layer->setAlpha(s.alpha))
3190 flags |= eTraversalNeeded;
3191 }
3192 if (what & layer_state_t::eColorChanged) {
3193 if (layer->setColor(s.color))
3194 flags |= eTraversalNeeded;
3195 }
Peiyong Lind3788632018-09-18 16:01:31 -07003196 if (what & layer_state_t::eColorTransformChanged) {
3197 if (layer->setColorTransform(s.colorTransform)) {
3198 flags |= eTraversalNeeded;
3199 }
3200 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003201 if (what & layer_state_t::eBackgroundColorChanged) {
3202 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3203 flags |= eTraversalNeeded;
3204 }
3205 }
chaviw8b3871a2017-11-01 17:41:01 -07003206 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003207 // TODO: b/109894387
3208 //
3209 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3210 // rotation. To see the problem observe that if we have a square parent, and a child
3211 // of the same size, then we rotate the child 45 degrees around it's center, the child
3212 // must now be cropped to a non rectangular 8 sided region.
3213 //
3214 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3215 // private API, and the WindowManager only uses rotation in one case, which is on a top
3216 // level layer in which cropping is not an issue.
3217 //
3218 // However given that abuse of rotation matrices could lead to surfaces extending outside
3219 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3220 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3221 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003222 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003223 flags |= eTraversalNeeded;
3224 }
3225 if (what & layer_state_t::eTransparentRegionChanged) {
3226 if (layer->setTransparentRegionHint(s.transparentRegion))
3227 flags |= eTraversalNeeded;
3228 }
3229 if (what & layer_state_t::eFlagsChanged) {
3230 if (layer->setFlags(s.flags, s.mask))
3231 flags |= eTraversalNeeded;
3232 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003233 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003234 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003235 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003236 if (what & layer_state_t::eCornerRadiusChanged) {
3237 if (layer->setCornerRadius(s.cornerRadius))
3238 flags |= eTraversalNeeded;
3239 }
chaviw8b3871a2017-11-01 17:41:01 -07003240 if (what & layer_state_t::eLayerStackChanged) {
3241 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3242 // We only allow setting layer stacks for top level layers,
3243 // everything else inherits layer stack from its parent.
3244 if (layer->hasParent()) {
3245 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3246 layer->getName().string());
3247 } else if (idx < 0) {
3248 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3249 "that also does not appear in the top level layer list. Something"
3250 " has gone wrong.", layer->getName().string());
3251 } else if (layer->setLayerStack(s.layerStack)) {
3252 mCurrentState.layersSortedByZ.removeAt(idx);
3253 mCurrentState.layersSortedByZ.add(layer);
3254 // we need traversal (state changed)
3255 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003256 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003257 }
3258 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003259 if (what & layer_state_t::eDeferTransaction_legacy) {
3260 if (s.barrierHandle_legacy != nullptr) {
3261 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3262 } else if (s.barrierGbp_legacy != nullptr) {
3263 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003264 if (authenticateSurfaceTextureLocked(gbp)) {
3265 const auto& otherLayer =
3266 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003267 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003268 } else {
3269 ALOGE("Attempt to defer transaction to to an"
3270 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003271 }
3272 }
chaviw8b3871a2017-11-01 17:41:01 -07003273 // We don't trigger a traversal here because if no other state is
3274 // changed, we don't want this to cause any more work
3275 }
chaviw8b3871a2017-11-01 17:41:01 -07003276 if (what & layer_state_t::eReparentChildren) {
3277 if (layer->reparentChildren(s.reparentHandle)) {
3278 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003279 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280 }
chaviw8b3871a2017-11-01 17:41:01 -07003281 if (what & layer_state_t::eDetachChildren) {
3282 layer->detachChildren();
3283 }
3284 if (what & layer_state_t::eOverrideScalingModeChanged) {
3285 layer->setOverrideScalingMode(s.overrideScalingMode);
3286 // We don't trigger a traversal here because if no other state is
3287 // changed, we don't want this to cause any more work
3288 }
Marissa Wall61c58622018-07-18 10:12:20 -07003289 if (what & layer_state_t::eTransformChanged) {
3290 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3291 }
3292 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3293 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3294 flags |= eTraversalNeeded;
3295 }
3296 if (what & layer_state_t::eCropChanged) {
3297 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3298 }
Marissa Wall861616d2018-10-22 12:52:23 -07003299 if (what & layer_state_t::eFrameChanged) {
3300 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3301 }
Marissa Wall61c58622018-07-18 10:12:20 -07003302 if (what & layer_state_t::eAcquireFenceChanged) {
3303 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3304 }
3305 if (what & layer_state_t::eDataspaceChanged) {
3306 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3307 }
3308 if (what & layer_state_t::eHdrMetadataChanged) {
3309 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3310 }
3311 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3312 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3313 }
3314 if (what & layer_state_t::eApiChanged) {
3315 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3316 }
3317 if (what & layer_state_t::eSidebandStreamChanged) {
3318 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3319 }
Robert Carr720e5062018-07-30 17:45:14 -07003320 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003321 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003322 layer->setInputInfo(s.inputInfo);
3323 flags |= eTraversalNeeded;
3324 } else {
3325 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3326 }
Robert Carr720e5062018-07-30 17:45:14 -07003327 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003328 if (what & layer_state_t::eMetadataChanged) {
3329 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3330 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003331 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3332 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3333 flags |= eTraversalNeeded;
3334 }
3335 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003336 // This has to happen after we reparent children because when we reparent to null we remove
3337 // child layers from current state and remove its relative z. If the children are reparented in
3338 // the same transaction, then we have to make sure we reparent the children first so we do not
3339 // lose its relative z order.
3340 if (what & layer_state_t::eReparent) {
3341 bool hadParent = layer->hasParent();
3342 if (layer->reparent(s.parentHandleForChild)) {
3343 if (!hadParent) {
3344 mCurrentState.layersSortedByZ.remove(layer);
3345 }
3346 flags |= eTransactionNeeded | eTraversalNeeded;
3347 }
3348 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003349 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003350 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3351 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003352 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3353 }
3354 }
Marissa Wall78b72202019-03-15 14:58:34 -07003355 bool bufferChanged = what & layer_state_t::eBufferChanged;
3356 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3357 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003358 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003359 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003360 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3361 if (success) {
3362 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3363 success = ClientCache::getInstance()
3364 .registerErasedRecipient(s.cachedBuffer,
3365 wp<ClientCache::ErasedRecipient>(this));
3366 if (!success) {
3367 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3368 }
3369 }
Marissa Wall78b72202019-03-15 14:58:34 -07003370 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003371 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003372 } else if (bufferChanged) {
3373 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003374 }
Marissa Wall78b72202019-03-15 14:58:34 -07003375 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003376 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003377 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003378 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003379 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003380 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3381 // Do not put anything that updates layer state or modifies flags after
3382 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003383 return flags;
3384}
3385
chaviw273171b2018-12-26 11:46:30 -08003386uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3387 uint32_t flags = 0;
3388 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3389 flags |= eTraversalNeeded;
3390 }
3391
chaviwa911b102019-02-14 10:18:33 -08003392 if (inputWindowCommands.syncInputWindows) {
3393 flags |= eTraversalNeeded;
3394 }
3395
Vishnu Nairec0ab382019-02-13 15:32:56 -08003396 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003397 return flags;
3398}
3399
chaviwfe94a222019-08-21 13:52:59 -07003400status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3401 sp<IBinder>* outHandle) {
3402 if (!mirrorFromHandle) {
3403 return NAME_NOT_FOUND;
3404 }
3405
3406 sp<Layer> mirrorLayer;
3407 sp<Layer> mirrorFrom;
3408 String8 uniqueName = getUniqueLayerName(String8("MirrorRoot"));
3409
3410 {
3411 Mutex::Autolock _l(mStateLock);
3412 mirrorFrom = fromHandle(mirrorFromHandle);
3413 if (!mirrorFrom) {
3414 return NAME_NOT_FOUND;
3415 }
3416
3417 status_t result = createContainerLayer(client, uniqueName, -1, -1, 0, LayerMetadata(),
3418 outHandle, &mirrorLayer);
3419 if (result != NO_ERROR) {
3420 return result;
3421 }
3422
3423 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3424 }
3425
3426 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3427}
3428
Marissa Wall2d814fb2019-04-09 18:52:57 +00003429status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3430 uint32_t h, PixelFormat format, uint32_t flags,
3431 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003432 sp<IGraphicBufferProducer>* gbp,
3433 const sp<IBinder>& parentHandle,
3434 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003435 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003436 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003437 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003438 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003439 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003440
Robert Carrc0df3122019-04-11 13:18:21 -07003441 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3442 "Expected only one of parentLayer or parentHandle to be non-null. "
3443 "Programmer error?");
3444
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003445 status_t result = NO_ERROR;
3446
3447 sp<Layer> layer;
3448
Cody Northropbc755282017-03-31 12:00:08 -06003449 String8 uniqueName = getUniqueLayerName(name);
3450
Evan Roskya1f1e152019-01-24 16:17:46 -08003451 bool primaryDisplayOnly = false;
3452
3453 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3454 // TODO b/64227542
3455 if (metadata.has(METADATA_WINDOW_TYPE)) {
3456 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3457 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003458 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003459 primaryDisplayOnly = true;
3460 }
3461 }
3462
Mathias Agopian3165cc22012-08-08 19:42:09 -07003463 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003464 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003465 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3466 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003467
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003468 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003469 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003470 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3471 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003472 break;
chaviw13fdc492017-06-27 12:40:18 -07003473 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003474 // check if buffer size is set for color layer.
3475 if (w > 0 || h > 0) {
3476 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3477 int(w), int(h));
3478 return BAD_VALUE;
3479 }
3480
Evan Roskya1f1e152019-01-24 16:17:46 -08003481 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3482 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003483 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003484 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003485 // check if buffer size is set for container layer.
3486 if (w > 0 || h > 0) {
3487 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3488 int(w), int(h));
3489 return BAD_VALUE;
3490 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003491 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3492 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003493 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003494 default:
3495 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003496 break;
3497 }
3498
Dan Stoza7d89d062015-04-30 13:29:25 -07003499 if (result != NO_ERROR) {
3500 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003501 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003502
Evan Roskya1f1e152019-01-24 16:17:46 -08003503 if (primaryDisplayOnly) {
3504 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003505 }
3506
Robert Carrb89ea9d2018-12-10 13:01:14 -08003507 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003508 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3509 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003510 if (result != NO_ERROR) {
3511 return result;
3512 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003513 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003514
3515 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003516 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517}
3518
Cody Northropbc755282017-03-31 12:00:08 -06003519String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3520{
3521 bool matchFound = true;
3522 uint32_t dupeCounter = 0;
3523
3524 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3525 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3526
Dan Stoza436ccf32018-06-21 12:10:12 -07003527 // Grab the state lock since we're accessing mCurrentState
3528 Mutex::Autolock lock(mStateLock);
3529
Cody Northropbc755282017-03-31 12:00:08 -06003530 // Loop over layers until we're sure there is no matching name
3531 while (matchFound) {
3532 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003533 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003534 if (layer->getName() == uniqueName) {
3535 matchFound = true;
3536 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3537 }
3538 });
3539 }
3540
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003541 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3542 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003543
3544 return uniqueName;
3545}
3546
Marissa Wallfd668622018-05-10 10:21:13 -07003547status_t SurfaceFlinger::createBufferQueueLayer(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, PixelFormat& format,
3550 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003551 sp<IGraphicBufferProducer>* gbp,
3552 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003554 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555 case PIXEL_FORMAT_TRANSPARENT:
3556 case PIXEL_FORMAT_TRANSLUCENT:
3557 format = PIXEL_FORMAT_RGBA_8888;
3558 break;
3559 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003560 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561 break;
3562 }
3563
chaviwb4c6e582019-08-16 14:35:07 -07003564 sp<BufferQueueLayer> layer;
3565 LayerCreationArgs args =
3566 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3567 args.textureName = getNewTexture();
3568 {
3569 // Grab the SF state lock during this since it's the only safe way to access
3570 // RenderEngine when creating a BufferLayerConsumer
3571 // TODO: Check if this lock is still needed here
3572 Mutex::Autolock lock(mStateLock);
3573 layer = getFactory().createBufferQueueLayer(args);
3574 }
3575
Marissa Wallfd668622018-05-10 10:21:13 -07003576 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003577 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003578 *handle = layer->getHandle();
3579 *gbp = layer->getProducer();
3580 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003581 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003582
Marissa Wallfd668622018-05-10 10:21:13 -07003583 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003584 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003585}
3586
Marissa Wall61c58622018-07-18 10:12:20 -07003587status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3588 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003589 LayerMetadata metadata, sp<IBinder>* handle,
3590 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07003591 LayerCreationArgs args =
3592 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3593 args.displayDevice = getDefaultDisplayDevice();
3594 args.textureName = getNewTexture();
3595 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003596 *handle = layer->getHandle();
3597 *outLayer = layer;
3598
3599 return NO_ERROR;
3600}
3601
Evan Roskya1f1e152019-01-24 16:17:46 -08003602status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
3603 uint32_t h, uint32_t flags, LayerMetadata metadata,
3604 sp<IBinder>* handle, sp<Layer>* outLayer) {
3605 *outLayer = getFactory().createColorLayer(
3606 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003607 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003608 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003609}
3610
Evan Roskya1f1e152019-01-24 16:17:46 -08003611status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
3612 uint32_t w, uint32_t h, uint32_t flags,
3613 LayerMetadata metadata, sp<IBinder>* handle,
3614 sp<Layer>* outLayer) {
3615 *outLayer = getFactory().createContainerLayer(
3616 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003617 *handle = (*outLayer)->getHandle();
3618 return NO_ERROR;
3619}
3620
3621
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003622void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003623 mLayersPendingRemoval.add(layer);
3624 mLayersRemoved = true;
3625 setTransactionFlags(eTransactionNeeded);
3626}
3627
Robert Carr695d5282018-12-18 15:27:58 -08003628void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003629{
Robert Carr2e102c92018-10-23 12:11:15 -07003630 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003631 // If a layer has a parent, we allow it to out-live it's handle
3632 // with the idea that the parent holds a reference and will eventually
3633 // be cleaned up. However no one cleans up the top-level so we do so
3634 // here.
3635 if (layer->getParent() == nullptr) {
3636 mCurrentState.layersSortedByZ.remove(layer);
3637 }
3638 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003639
3640 auto it = mLayersByLocalBinderToken.begin();
3641 while (it != mLayersByLocalBinderToken.end()) {
3642 if (it->second == layer) {
3643 it = mLayersByLocalBinderToken.erase(it);
3644 } else {
3645 it++;
3646 }
3647 }
3648
Robert Carr695d5282018-12-18 15:27:58 -08003649 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003650}
3651
Mathias Agopianb60314a2012-04-10 22:09:54 -07003652// ---------------------------------------------------------------------------
3653
Andy McFadden13a082e2012-08-24 10:16:42 -07003654void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003655 const auto display = getDefaultDisplayDeviceLocked();
3656 if (!display) return;
3657
3658 const sp<IBinder> token = display->getDisplayToken().promote();
3659 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003660
Jesse Hall01e29052013-02-19 16:13:35 -08003661 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003662 Vector<ComposerState> state;
3663 Vector<DisplayState> displays;
3664 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003665 d.what = DisplayState::eDisplayProjectionChanged |
3666 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003667 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003668 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003669 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003670 d.frame.makeInvalid();
3671 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003672 d.width = 0;
3673 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003674 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003675 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3676 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003677
Dominik Laskowskie9774092018-12-11 10:04:24 -08003678 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003679
Dominik Laskowski83b88212018-12-11 13:34:06 -08003680 const nsecs_t vsyncPeriod = getVsyncPeriod();
3681 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003682
Brian Andersond0010582017-03-07 13:20:31 -08003683 // Use phase of 0 since phase is not known.
3684 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003685 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003686 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003687}
3688
3689void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003690 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003691 postMessageAsync(
3692 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003693}
3694
Ady Abraham27c70212019-06-11 10:52:26 -07003695void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3696 if (mHWCVsyncState != enabled) {
3697 getHwComposer().setVsyncEnabled(displayId, enabled);
3698 mHWCVsyncState = enabled;
3699 }
3700}
3701
Dominik Laskowskie9774092018-12-11 10:04:24 -08003702void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003703 if (display->isVirtual()) {
3704 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003705 return;
3706 }
3707
Dominik Laskowski075d3172018-05-24 15:50:06 -07003708 const auto displayId = display->getId();
3709 LOG_ALWAYS_FATAL_IF(!displayId);
3710
Dominik Laskowski34157762018-10-31 13:07:19 -07003711 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003712
3713 int currentMode = display->getPowerMode();
3714 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003715 return;
3716 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003717
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003718 display->setPowerMode(mode);
3719
Lloyd Pique4dccc412018-01-22 17:21:36 -08003720 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003721 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003722 }
3723
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003724 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003725 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003726 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003727 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003728 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003729 mScheduler->onScreenAcquired(mAppConnectionHandle);
3730 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003731 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003732
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003733 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003734 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003735 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003736
3737 struct sched_param param = {0};
3738 param.sched_priority = 1;
3739 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3740 ALOGW("Couldn't set SCHED_FIFO on display on");
3741 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003742 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003743 // Turn off the display
3744 struct sched_param param = {0};
3745 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3746 ALOGW("Couldn't set SCHED_OTHER on display off");
3747 }
3748
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003749 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003750 mScheduler->disableHardwareVsync(true);
3751 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003752 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003753
Ady Abraham27c70212019-06-11 10:52:26 -07003754 // Make sure HWVsync is disabled before turning off the display
3755 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3756
Dominik Laskowski075d3172018-05-24 15:50:06 -07003757 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003758 mVisibleRegionsDirty = true;
3759 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003760 } else if (mode == HWC_POWER_MODE_DOZE ||
3761 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003762 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003763 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003764 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003765 mScheduler->onScreenAcquired(mAppConnectionHandle);
3766 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003767 }
3768 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3769 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003770 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003771 mScheduler->disableHardwareVsync(true);
3772 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003773 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003774 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003775 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003776 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003777 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003778 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003779
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003780 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003781 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003782 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003783 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003784 }
3785
Dominik Laskowski34157762018-10-31 13:07:19 -07003786 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003787}
3788
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003789void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003790 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003791 const auto display = getDisplayDevice(displayToken);
3792 if (!display) {
3793 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3794 displayToken.get());
3795 } else if (display->isVirtual()) {
3796 ALOGW("Attempt to set power mode %d for virtual display", mode);
3797 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003798 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003799 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003800 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003801}
3802
3803// ---------------------------------------------------------------------------
3804
Dominik Laskowskic2867142019-01-21 11:33:38 -08003805status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3806 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003807 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003808
Mathias Agopianbd115332013-04-18 16:41:04 -07003809 IPCThreadState* ipc = IPCThreadState::self();
3810 const int pid = ipc->getCallingPid();
3811 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003812
Mathias Agopianbd115332013-04-18 16:41:04 -07003813 if ((uid != AID_SHELL) &&
3814 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003815 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3816 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003817 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003818 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003819 // (this would indicate SF is stuck, but we want to be able to
3820 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003821 status_t err = mStateLock.timedLock(s2ns(1));
3822 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003823 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003824 StringAppendF(&result,
3825 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3826 "(no locks held)\n",
3827 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003828 }
3829
Dominik Laskowskic2867142019-01-21 11:33:38 -08003830 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07003831
Dominik Laskowskic2867142019-01-21 11:33:38 -08003832 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003833 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003834 {"--dispsync"s,
3835 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003836 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003837 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3838 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3839 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3840 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3841 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3842 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003843 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003844 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3845 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003846
Dominik Laskowskic2867142019-01-21 11:33:38 -08003847 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003848
Dominik Laskowski46470112019-08-02 13:13:11 -07003849 const auto it = dumpers.find(flag);
3850 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003851 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003852 } else if (!asProto) {
3853 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003854 }
3855
Mathias Agopian9795c422009-08-26 16:36:26 -07003856 if (locked) {
3857 mStateLock.unlock();
3858 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003859
Dominik Laskowski46470112019-08-02 13:13:11 -07003860 if (it == dumpers.end()) {
3861 const LayersProto layersProto = dumpProtoFromMainThread();
3862 if (asProto) {
3863 result.append(layersProto.SerializeAsString());
3864 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003865 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003866 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3867 result.append(LayerProtoParser::layerTreeToString(layerTree));
3868 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003869 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003870 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003871 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003872 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003873 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003874 return NO_ERROR;
3875}
3876
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003877status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3878 if (asProto && mTracing.isEnabled()) {
3879 mTracing.writeToFileAsync();
3880 }
3881
3882 return doDump(fd, DumpArgs(), asProto);
3883}
3884
Dominik Laskowskic2867142019-01-21 11:33:38 -08003885void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003886 mCurrentState.traverseInZOrder(
3887 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003888}
3889
Dominik Laskowskic2867142019-01-21 11:33:38 -08003890void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003891 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003892
Dominik Laskowskic2867142019-01-21 11:33:38 -08003893 if (args.size() > 1) {
3894 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003895 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003896 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003897 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003898 }
Robert Carr2047fae2016-11-28 14:09:09 -08003899 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003900 } else {
3901 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003902 }
3903}
3904
Dominik Laskowskic2867142019-01-21 11:33:38 -08003905void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08003906 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003907 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003908 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003909 }
Robert Carr2047fae2016-11-28 14:09:09 -08003910 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003911
Svetoslavd85084b2014-03-20 10:28:31 -07003912 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003913}
3914
Dominik Laskowskic2867142019-01-21 11:33:38 -08003915void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3916 mTimeStats->parseArgs(asProto, args, result);
3917}
3918
Jamie Gennis6547ff42013-07-16 20:12:42 -07003919// This should only be called from the main thread. Otherwise it would need
3920// the lock and should use mCurrentState rather than mDrawingState.
3921void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003922 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003923 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003924 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003925
3926 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3927}
3928
Yiwei Zhang5434a782018-12-05 18:06:32 -08003929void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003930 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003931
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003932 if (isLayerTripleBufferingDisabled())
3933 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003934
Yiwei Zhang5434a782018-12-05 18:06:32 -08003935 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3936 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3937 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3938 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3939 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3940 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003941 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003942}
3943
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003944void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003945 mScheduler->dump(result);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003946 StringAppendF(&result, "+ Refresh rate switching: %s\n",
3947 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowski98041832019-08-01 18:35:59 -07003948 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
3949
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003950 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003951 result.append("\n");
3952
Ana Krulec757f63a2019-01-25 10:46:18 -08003953 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003954 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003955 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003956 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003957
Ady Abraham42b3beb2019-07-09 18:09:52 -07003958 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003959 for (int32_t configId : mAllowedDisplayConfigs) {
3960 StringAppendF(&result, "%" PRIu32 " Hz, ",
3961 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003962 }
3963 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3964 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003965
Ana Krulecc2870422019-01-29 19:00:58 -08003966 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003967}
3968
Yiwei Zhang5434a782018-12-05 18:06:32 -08003969void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3970 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003971 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3972 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003973 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003974 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003975 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003976 }
David Sodman4a36e932017-11-07 14:29:47 -08003977 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003978 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003979 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003980 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3981 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003982}
3983
Dan Stozae77c7662016-05-13 11:37:28 -07003984void SurfaceFlinger::recordBufferingStats(const char* layerName,
3985 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003986 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3987 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003988 for (const auto& segment : history) {
3989 if (!segment.usedThirdBuffer) {
3990 stats.twoBufferTime += segment.totalTime;
3991 }
3992 if (segment.occupancyAverage < 1.0f) {
3993 stats.doubleBufferedTime += segment.totalTime;
3994 } else if (segment.occupancyAverage < 2.0f) {
3995 stats.tripleBufferedTime += segment.totalTime;
3996 }
3997 ++stats.numSegments;
3998 stats.totalTime += segment.totalTime;
3999 }
4000}
4001
Yiwei Zhang5434a782018-12-05 18:06:32 -08004002void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4003 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004004
4005 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4006 const size_t count = currentLayers.size();
4007 for (size_t i=0 ; i<count ; i++) {
4008 currentLayers[i]->dumpFrameEvents(result);
4009 }
4010}
4011
Yiwei Zhang5434a782018-12-05 18:06:32 -08004012void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004013 result.append("Buffering stats:\n");
4014 result.append(" [Layer name] <Active time> <Two buffer> "
4015 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004016 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004017 typedef std::tuple<std::string, float, float, float> BufferTuple;
4018 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004019 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004020 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004021 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004022 if (stats.numSegments == 0) {
4023 continue;
4024 }
4025 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4026 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4027 stats.totalTime;
4028 float doubleBufferRatio = static_cast<float>(
4029 stats.doubleBufferedTime) / stats.totalTime;
4030 float tripleBufferRatio = static_cast<float>(
4031 stats.tripleBufferedTime) / stats.totalTime;
4032 sorted.insert({activeTime, {name, twoBufferRatio,
4033 doubleBufferRatio, tripleBufferRatio}});
4034 }
4035 for (const auto& sortedPair : sorted) {
4036 float activeTime = sortedPair.first;
4037 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004038 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4039 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004040 }
4041 result.append("\n");
4042}
4043
Yiwei Zhang5434a782018-12-05 18:06:32 -08004044void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004045 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004046 const auto displayId = display->getId();
4047 if (!displayId) {
4048 continue;
4049 }
4050 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004051 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004052 continue;
4053 }
4054
Yiwei Zhang5434a782018-12-05 18:06:32 -08004055 StringAppendF(&result,
4056 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4057 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004058 uint8_t port;
4059 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004060 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004061 result.append("no identification data\n");
4062 continue;
4063 }
4064
4065 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004066 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004067 continue;
4068 }
4069
4070 const auto edid = parseEdid(data);
4071 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004072 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004073 continue;
4074 }
4075
Yiwei Zhang5434a782018-12-05 18:06:32 -08004076 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004077 result.append(edid->displayName.data(), edid->displayName.length());
4078 result.append("\"\n");
4079 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004080}
4081
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004082void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4083 std::string& result) const {
4084 hwc2_display_t hwcDisplayId;
4085 uint8_t port;
4086 DisplayIdentificationData data;
4087
4088 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4089 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4090 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4091 }
4092}
4093
Yiwei Zhang5434a782018-12-05 18:06:32 -08004094void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004095 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004096 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4097 StringAppendF(&result, "DisplayColorSetting: %s\n",
4098 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004099
4100 // TODO: print out if wide-color mode is active or not
4101
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004102 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004103 const auto displayId = display->getId();
4104 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004105 continue;
4106 }
4107
Yiwei Zhang5434a782018-12-05 18:06:32 -08004108 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004109 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004110 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004111 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004112 }
4113
Lloyd Pique32cbe282018-10-19 13:09:22 -07004114 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004115 StringAppendF(&result, " Current color mode: %s (%d)\n",
4116 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004117 }
4118 result.append("\n");
4119}
4120
Vishnu Nair8406fd72019-07-30 11:29:31 -07004121LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004122 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004123 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004124 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004125 layer->writeToProtoDrawingState(layerProto, traceFlags);
4126 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004127 });
4128
4129 return layersProto;
4130}
4131
Vishnu Nair0f085c62019-08-30 08:49:12 -07004132void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4133 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4134 // it.
4135 LayerProto* rootProto = layersProto.add_layers();
4136 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4137 rootProto->set_id(offscreenRootLayerId);
4138 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004139 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004140
4141 for (Layer* offscreenLayer : mOffscreenLayers) {
4142 // Add layer as child of the fake root
4143 rootProto->add_children(offscreenLayer->sequence);
4144
4145 // Add layer
4146 LayerProto* layerProto = layersProto.add_layers();
4147 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4148 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4149 traceFlags);
4150 layerProto->set_parent(offscreenRootLayerId);
4151
4152 // Add children
4153 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4154 if (layer == offscreenLayer) {
4155 return;
4156 }
4157 LayerProto* childProto = layersProto.add_layers();
4158 layer->writeToProtoDrawingState(childProto, traceFlags);
4159 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4160 });
4161 }
4162}
4163
Vishnu Nair8406fd72019-07-30 11:29:31 -07004164LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4165 LayersProto layersProto;
4166 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4167 return layersProto;
4168}
4169
Vishnu Nair0f085c62019-08-30 08:49:12 -07004170void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4171 result.append("Offscreen Layers:\n");
4172 postMessageSync(new LambdaMessage([&]() {
4173 for (Layer* offscreenLayer : mOffscreenLayers) {
4174 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4175 layer->dumpCallingUidPid(result);
4176 });
4177 }
4178 }));
4179}
4180
Dominik Laskowskic2867142019-01-21 11:33:38 -08004181void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4182 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004183 Colorizer colorizer(colorize);
4184
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004185 // figure out if we're stuck somewhere
4186 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004187 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004188 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4189
4190 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004191 * Dump library configuration.
4192 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004193
4194 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004195 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004196 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004197 appendSfConfigString(result);
4198 appendUiConfigString(result);
4199 appendGuiConfigString(result);
4200 result.append("\n");
4201
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004202 result.append("\nDisplay identification data:\n");
4203 dumpDisplayIdentificationData(result);
4204
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004205 result.append("\nWide-Color information:\n");
4206 dumpWideColorInfo(result);
4207
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004208 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004209 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004210 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004211 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004212 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004213
Andy McFadden41d67d72014-04-25 16:58:34 -07004214 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004215 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004216 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004217 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004218 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004219
Dan Stozab90cf072015-03-05 11:05:59 -08004220 dumpStaticScreenStats(result);
4221 result.append("\n");
4222
Alec Mouri40189b02019-03-05 15:07:54 -08004223 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4224 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4225 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004226
Dan Stozae77c7662016-05-13 11:37:28 -07004227 dumpBufferingStats(result);
4228
Andy McFadden4803b742012-09-24 19:07:20 -07004229 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004230 * Dump the visible layer list
4231 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004232 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004233 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004234 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4235 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004237
Chia-I Wu2f884132018-09-13 15:17:58 -07004238 {
Lloyd Pique207def92019-02-28 16:09:52 -08004239 StringAppendF(&result, "Composition layers\n");
4240 mDrawingState.traverseInZOrder([&](Layer* layer) {
4241 auto compositionLayer = layer->getCompositionLayer();
4242 if (compositionLayer) compositionLayer->dump(result);
4243 });
4244 }
4245
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004246 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004247 * Dump Display state
4248 */
4249
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004250 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004251 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004252 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004253 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004254 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004255 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004256 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004257
4258 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004259 * Dump CompositionEngine state
4260 */
4261
4262 mCompositionEngine->dump(result);
4263
4264 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265 * Dump SurfaceFlinger global state
4266 */
4267
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004269 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004270 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004271
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004272 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004273
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004274 DebugEGLImageTracker::getInstance()->dump(result);
4275
Dominik Laskowski075d3172018-05-24 15:50:06 -07004276 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004277 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4278 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004279 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4280 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004281 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004282 StringAppendF(&result,
4283 " transaction-flags : %08x\n"
4284 " gpu_to_cpu_unsupported : %d\n",
4285 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004286
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004287 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004288 displayId && getHwComposer().isConnected(*displayId)) {
4289 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004290 StringAppendF(&result,
4291 " refresh-rate : %f fps\n"
4292 " x-dpi : %f\n"
4293 " y-dpi : %f\n",
4294 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4295 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004296 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297
Yiwei Zhang5434a782018-12-05 18:06:32 -08004298 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299
Dan Stozae22aec72016-08-01 13:20:59 -07004300 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004301 * Tracing state
4302 */
4303 mTracing.dump(result);
4304 result.append("\n");
4305
4306 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004307 * HWC layer minidump
4308 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004309 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004310 const auto displayId = display->getId();
4311 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004312 continue;
4313 }
4314
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004316 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004317 const sp<DisplayDevice> displayDevice = display;
4318 mCurrentState.traverseInZOrder(
4319 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004320 result.append("\n");
4321 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004322
4323 /*
4324 * Dump HWComposer state
4325 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004326 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004327 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004328 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004329 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004330 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004331 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332
4333 /*
4334 * Dump gralloc state
4335 */
4336 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4337 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004338
4339 /*
4340 * Dump VrFlinger state if in use.
4341 */
4342 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4343 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004345 result.append("\n");
4346 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004347
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004348 result.append(mTimeStats->miniDump());
4349 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004350}
4351
Chia-I Wu28f320b2018-05-03 11:02:56 -07004352void SurfaceFlinger::updateColorMatrixLocked() {
4353 mat4 colorMatrix;
4354 if (mGlobalSaturationFactor != 1.0f) {
4355 // Rec.709 luma coefficients
4356 float3 luminance{0.213f, 0.715f, 0.072f};
4357 luminance *= 1.0f - mGlobalSaturationFactor;
4358 mat4 saturationMatrix = mat4(
4359 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4360 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4361 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4362 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4363 );
4364 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4365 } else {
4366 colorMatrix = mClientColorMatrix * mDaltonizer();
4367 }
4368
4369 if (mCurrentState.colorMatrix != colorMatrix) {
4370 mCurrentState.colorMatrix = colorMatrix;
4371 mCurrentState.colorMatrixChanged = true;
4372 setTransactionFlags(eTransactionNeeded);
4373 }
4374}
4375
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004376status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004377#pragma clang diagnostic push
4378#pragma clang diagnostic error "-Wswitch-enum"
4379 switch (static_cast<ISurfaceComposerTag>(code)) {
4380 // These methods should at minimum make sure that the client requested
4381 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004382 case BOOT_FINISHED:
4383 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004384 case CREATE_DISPLAY:
4385 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004386 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004387 case GET_ANIMATION_FRAME_STATS:
4388 case GET_HDR_CAPABILITIES:
4389 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004390 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004391 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004392 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004393 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004394 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004395 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004396 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004397 case GET_DISPLAYED_CONTENT_SAMPLE:
4398 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004399 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4400 IPCThreadState* ipc = IPCThreadState::self();
4401 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4402 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004403 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004404 }
Robert Carr1db73f62016-12-21 12:58:51 -08004405 return OK;
4406 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004407 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004408 IPCThreadState* ipc = IPCThreadState::self();
4409 const int pid = ipc->getCallingPid();
4410 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004411 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4412 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004413 return PERMISSION_DENIED;
4414 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004415 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004416 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004417 // Used by apps to hook Choreographer to SurfaceFlinger.
4418 case CREATE_DISPLAY_EVENT_CONNECTION:
4419 // The following calls are currently used by clients that do not
4420 // request necessary permissions. However, they do not expose any secret
4421 // information, so it is OK to pass them.
4422 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004423 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004424 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004425 case GET_PHYSICAL_DISPLAY_IDS:
4426 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004427 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004428 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004429 case GET_DISPLAY_CONFIGS:
4430 case GET_DISPLAY_STATS:
4431 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4432 // Calling setTransactionState is safe, because you need to have been
4433 // granted a reference to Client* and Handle* to do anything with it.
4434 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004435 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004436 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004437 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004438 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004439 case IS_WIDE_COLOR_DISPLAY:
4440 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4441 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004442 return OK;
4443 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004444 case CAPTURE_LAYERS: {
4445 IPCThreadState* ipc = IPCThreadState::self();
4446 const int pid = ipc->getCallingPid();
4447 const int uid = ipc->getCallingUid();
4448 // allow media to capture layer for video thumbnails
4449 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4450 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4451 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4452 return PERMISSION_DENIED;
4453 }
4454 return OK;
4455 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004456 case CAPTURE_SCREEN:
4457 case ADD_REGION_SAMPLING_LISTENER:
4458 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004459 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004460 IPCThreadState* ipc = IPCThreadState::self();
4461 const int pid = ipc->getCallingPid();
4462 const int uid = ipc->getCallingUid();
4463 if ((uid != AID_GRAPHICS) &&
4464 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4465 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4466 return PERMISSION_DENIED;
4467 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004468 return OK;
4469 }
4470 // The following codes are deprecated and should never be allowed to access SF.
4471 case CONNECT_DISPLAY_UNUSED:
4472 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4473 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4474 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004475 }
chaviw93df2ea2019-04-30 16:45:12 -07004476 case CAPTURE_SCREEN_BY_ID: {
4477 IPCThreadState* ipc = IPCThreadState::self();
4478 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004479 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004480 return OK;
4481 }
4482 return PERMISSION_DENIED;
4483 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004485
4486 // These codes are used for the IBinder protocol to either interrogate the recipient
4487 // side of the transaction for its canonical interface descriptor or to dump its state.
4488 // We let them pass by default.
4489 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4490 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4491 code == IBinder::SYSPROPS_TRANSACTION) {
4492 return OK;
4493 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004494 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004495 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004496 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004497 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4498 return OK;
4499 }
4500 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4501 return PERMISSION_DENIED;
4502#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004503}
4504
Ana Krulec13be8ad2018-08-21 02:43:56 +00004505status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4506 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004507 status_t credentialCheck = CheckTransactCodeCredentials(code);
4508 if (credentialCheck != OK) {
4509 return credentialCheck;
4510 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004512 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4513 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004514 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004515 IPCThreadState* ipc = IPCThreadState::self();
4516 const int uid = ipc->getCallingUid();
4517 if (CC_UNLIKELY(uid != AID_SYSTEM
4518 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004519 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004520 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004521 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 return PERMISSION_DENIED;
4523 }
4524 int n;
4525 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004526 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004527 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 return NO_ERROR;
4529 case 1002: // SHOW_UPDATES
4530 n = data.readInt32();
4531 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004532 invalidateHwcGeometry();
4533 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004535 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004536 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004537 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004538 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004539 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004540 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004541 setTransactionFlags(
4542 eTransactionNeeded|
4543 eDisplayTransactionNeeded|
4544 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004545 return NO_ERROR;
4546 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004547 case 1006:{ // send empty update
4548 signalRefresh();
4549 return NO_ERROR;
4550 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004551 case 1008: // toggle use of hw composer
4552 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004553 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004554 invalidateHwcGeometry();
4555 repaintEverything();
4556 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004557 case 1009: // toggle use of transform hint
4558 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004559 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004560 invalidateHwcGeometry();
4561 repaintEverything();
4562 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004564 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004565 reply->writeInt32(0);
4566 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004567 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004568 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004569 return NO_ERROR;
4570 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004571 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004572 if (!display) {
4573 return NAME_NOT_FOUND;
4574 }
4575
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004576 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004577 return NO_ERROR;
4578 }
4579 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004580 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004581 // daltonize
4582 n = data.readInt32();
4583 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004584 case 1:
4585 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4586 break;
4587 case 2:
4588 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4589 break;
4590 case 3:
4591 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4592 break;
4593 default:
4594 mDaltonizer.setType(ColorBlindnessType::None);
4595 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004596 }
4597 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004598 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004599 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004600 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004601 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004602
4603 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004604 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004605 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004606 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004607 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004608 // apply a color matrix
4609 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004610 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004611 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004612 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004613 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004614 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004615 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004616 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004617 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004618 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004619 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004620
4621 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4622 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004623 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004624 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4625 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4626 }
4627
Chia-I Wu28f320b2018-05-03 11:02:56 -07004628 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004629 return NO_ERROR;
4630 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004631 case 1016: { // Unused.
4632 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004633 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004634 case 1017: {
4635 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004636 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004637 return NO_ERROR;
4638 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004639 case 1018: { // Modify Choreographer's phase offset
4640 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004641 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004642 return NO_ERROR;
4643 }
4644 case 1019: { // Modify SurfaceFlinger's phase offset
4645 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004646 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004647 return NO_ERROR;
4648 }
Irvel468051e2016-06-13 16:44:44 -07004649 case 1020: { // Layer updates interceptor
4650 n = data.readInt32();
4651 if (n) {
4652 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004653 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004654 }
4655 else{
4656 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004657 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004658 }
4659 return NO_ERROR;
4660 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004661 case 1021: { // Disable HWC virtual displays
4662 n = data.readInt32();
4663 mUseHwcVirtualDisplays = !n;
4664 return NO_ERROR;
4665 }
Romain Guy0147a172017-06-01 13:53:56 -07004666 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004667 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004668 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004669
Chia-I Wu28f320b2018-05-03 11:02:56 -07004670 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004671 return NO_ERROR;
4672 }
Romain Guy54f154a2017-10-24 21:40:32 +01004673 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004674 int32_t colorMode;
4675
Chia-I Wu0d711262018-05-21 15:19:35 -07004676 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004677 if (data.readInt32(&colorMode) == NO_ERROR) {
4678 mForceColorMode = static_cast<ColorMode>(colorMode);
4679 }
Romain Guy54f154a2017-10-24 21:40:32 +01004680 invalidateHwcGeometry();
4681 repaintEverything();
4682 return NO_ERROR;
4683 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004684 // Deprecate, use 1030 to check whether the device is color managed.
4685 case 1024: {
4686 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004687 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004688 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004689 n = data.readInt32();
4690 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004691 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004692 Mutex::Autolock lock(mStateLock);
4693 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004694 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004695 reply->writeInt32(NO_ERROR);
4696 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004697 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004698 bool writeFile = false;
4699 {
4700 Mutex::Autolock lock(mStateLock);
4701 mTracingEnabledChanged = true;
4702 writeFile = mTracing.disable();
4703 }
4704
4705 if (writeFile) {
4706 reply->writeInt32(mTracing.writeToFile());
4707 } else {
4708 reply->writeInt32(NO_ERROR);
4709 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004710 }
4711 return NO_ERROR;
4712 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004713 case 1026: { // Get layer tracing status
4714 reply->writeBool(mTracing.isEnabled());
4715 return NO_ERROR;
4716 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004717 // Is a DisplayColorSetting supported?
4718 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004719 const auto display = getDefaultDisplayDevice();
4720 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004721 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004722 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004723
4724 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4725 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004726 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004727 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004728 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004729 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004730 reply->writeBool(true);
4731 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004732 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004733 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004734 break;
4735 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004736 reply->writeBool(
4737 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004738 break;
4739 }
4740 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004741 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004742 // Is VrFlinger active?
4743 case 1028: {
4744 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004745 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004746 return NO_ERROR;
4747 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004748 // Set buffer size for SF tracing (value in KB)
4749 case 1029: {
4750 n = data.readInt32();
4751 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4752 ALOGW("Invalid buffer size: %d KB", n);
4753 reply->writeInt32(BAD_VALUE);
4754 return BAD_VALUE;
4755 }
4756
4757 ALOGD("Updating trace buffer to %d KB", n);
4758 mTracing.setBufferSize(n * 1024);
4759 reply->writeInt32(NO_ERROR);
4760 return NO_ERROR;
4761 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004762 // Is device color managed?
4763 case 1030: {
4764 reply->writeBool(useColorManagement);
4765 return NO_ERROR;
4766 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004767 // Override default composition data space
4768 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4769 // && adb shell stop zygote && adb shell start zygote
4770 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4771 // adb shell stop zygote && adb shell start zygote
4772 case 1031: {
4773 Mutex::Autolock _l(mStateLock);
4774 n = data.readInt32();
4775 if (n) {
4776 n = data.readInt32();
4777 if (n) {
4778 Dataspace dataspace = static_cast<Dataspace>(n);
4779 if (!validateCompositionDataspace(dataspace)) {
4780 return BAD_VALUE;
4781 }
4782 mDefaultCompositionDataspace = dataspace;
4783 }
4784 n = data.readInt32();
4785 if (n) {
4786 Dataspace dataspace = static_cast<Dataspace>(n);
4787 if (!validateCompositionDataspace(dataspace)) {
4788 return BAD_VALUE;
4789 }
4790 mWideColorGamutCompositionDataspace = dataspace;
4791 }
4792 } else {
4793 // restore composition data space.
4794 mDefaultCompositionDataspace = defaultCompositionDataspace;
4795 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4796 }
4797 return NO_ERROR;
4798 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004799 // Set trace flags
4800 case 1033: {
4801 n = data.readUint32();
4802 ALOGD("Updating trace flags to 0x%x", n);
4803 mTracing.setTraceFlags(n);
4804 reply->writeInt32(NO_ERROR);
4805 return NO_ERROR;
4806 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004807 case 1034: {
4808 // TODO(b/129297325): expose this via developer menu option
4809 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004810 if (n && !mRefreshRateOverlay &&
4811 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004812 RefreshRateType type;
4813 {
4814 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4815 type = mDesiredActiveConfig.type;
4816 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004817 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004818 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004819 } else if (!n) {
4820 mRefreshRateOverlay.reset();
4821 }
4822 return NO_ERROR;
4823 }
Ady Abraham34392f72019-04-10 11:29:27 -07004824 case 1035: {
4825 n = data.readInt32();
4826 mDebugDisplayConfigSetByBackdoor = false;
4827 if (n >= 0) {
4828 const auto displayToken = getInternalDisplayToken();
4829 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4830 if (result != NO_ERROR) {
4831 return result;
4832 }
4833 mDebugDisplayConfigSetByBackdoor = true;
4834 }
4835 return NO_ERROR;
4836 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004837 }
4838 }
4839 return err;
4840}
4841
Steven Thomas6d8110b2017-08-31 18:24:21 -07004842void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004843 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004844 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004845}
4846
Ana Krulec7d1d6832018-12-27 11:10:09 -08004847void SurfaceFlinger::repaintEverythingForHWC() {
4848 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004849 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004850}
4851
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004852// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4853class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004854public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004855 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4856 ~WindowDisconnector() {
4857 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004858 }
4859
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004860private:
4861 ANativeWindow* mWindow;
4862 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004863};
4864
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004865status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004866 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4867 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004868 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004869 uint32_t reqWidth, uint32_t reqHeight,
4870 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004871 ISurfaceComposer::Rotation rotation,
4872 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004873 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004874
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004875 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004876
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004877 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4878
Chia-I Wu20261cb2018-08-23 12:55:44 -07004879 sp<DisplayDevice> display;
4880 {
4881 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004882
Chia-I Wu20261cb2018-08-23 12:55:44 -07004883 display = getDisplayDeviceLocked(displayToken);
4884 if (!display) return BAD_VALUE;
4885
Chia-I Wucb023152018-08-28 12:57:23 -07004886 // set the requested width/height to the logical display viewport size
4887 // by default
4888 if (reqWidth == 0 || reqHeight == 0) {
4889 reqWidth = uint32_t(display->getViewport().width());
4890 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004891 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004892 }
4893
Peiyong Lin0e003c92018-09-17 11:09:51 -07004894 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004895 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004896
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004897 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4898 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004899 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004900 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004901}
4902
chaviw93df2ea2019-04-30 16:45:12 -07004903static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4904 switch (colorMode) {
4905 case ColorMode::DISPLAY_P3:
4906 case ColorMode::BT2100_PQ:
4907 case ColorMode::BT2100_HLG:
4908 case ColorMode::DISPLAY_BT2020:
4909 return Dataspace::DISPLAY_P3;
4910 default:
4911 return Dataspace::V0_SRGB;
4912 }
4913}
4914
4915const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4916 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4917 if (displayToken) {
4918 return getDisplayDeviceLocked(displayToken);
4919 }
4920 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4921 // may not have a displayId.
4922 for (const auto& [token, display] : mDisplays) {
4923 if (display->getLayerStack() == displayOrLayerStack) {
4924 return display;
4925 }
4926 }
4927 return nullptr;
4928}
4929
4930status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4931 sp<GraphicBuffer>* outBuffer) {
4932 sp<DisplayDevice> display;
4933 uint32_t width;
4934 uint32_t height;
4935 ui::Transform::orientation_flags captureOrientation;
4936 {
4937 Mutex::Autolock _l(mStateLock);
4938 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4939 if (!display) {
4940 return BAD_VALUE;
4941 }
4942
4943 width = uint32_t(display->getViewport().width());
4944 height = uint32_t(display->getViewport().height());
4945
4946 captureOrientation = fromSurfaceComposerRotation(
4947 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004948 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4949 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4950 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4951 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4952 }
chaviw93df2ea2019-04-30 16:45:12 -07004953 *outDataspace =
4954 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4955 }
4956
4957 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4958 false /* captureSecureLayers */);
4959
4960 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4961 std::placeholders::_1);
4962 bool ignored = false;
4963 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4964 false /* useIdentityTransform */,
4965 ignored /* outCapturedSecureLayers */);
4966}
4967
Robert Carr866455f2019-04-02 16:28:26 -07004968status_t SurfaceFlinger::captureLayers(
4969 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4970 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4971 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4972 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004973 ATRACE_CALL();
4974
4975 class LayerRenderArea : public RenderArea {
4976 public:
Robert Carr578038f2018-03-09 12:25:24 -08004977 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004978 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4979 bool childrenOnly)
4980 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004981 mLayer(layer),
4982 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004983 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004984 mFlinger(flinger),
4985 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004986 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004987 Rect getBounds() const override {
4988 const Layer::State& layerState(mLayer->getDrawingState());
4989 return mLayer->getBufferSize(layerState);
4990 }
Marissa Wall61c58622018-07-18 10:12:20 -07004991 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004992 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004993 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004994 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004995 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004996 }
chaviwa76b2712017-09-20 12:02:26 -07004997 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004998 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004999 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005000 Rect getSourceCrop() const override {
5001 if (mCrop.isEmpty()) {
5002 return getBounds();
5003 } else {
5004 return mCrop;
5005 }
5006 }
Robert Carr578038f2018-03-09 12:25:24 -08005007 class ReparentForDrawing {
5008 public:
5009 const sp<Layer>& oldParent;
5010 const sp<Layer>& newParent;
5011
Vishnu Nair4351ad52019-02-11 14:13:02 -08005012 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5013 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005014 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005015 // Compute and cache the bounds for the new parent layer.
5016 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005017 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005018 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005019 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005020 };
5021
5022 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005023 const Rect sourceCrop = getSourceCrop();
5024 // no need to check rotation because there is none
5025 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5026 sourceCrop.height() != getReqHeight();
5027
Robert Carr578038f2018-03-09 12:25:24 -08005028 if (!mChildrenOnly) {
5029 mTransform = mLayer->getTransform().inverse();
5030 drawLayers();
5031 } else {
5032 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07005033 // In the "childrenOnly" case we reparent the children to a screenshot
5034 // layer which has no properties set and which does not draw.
5035 sp<ContainerLayer> screenshotParentLayer =
5036 mFlinger->getFactory().createContainerLayer(
5037 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5038 bounds.getWidth(), bounds.getHeight(), 0,
5039 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005040
Vishnu Nair4351ad52019-02-11 14:13:02 -08005041 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005042 drawLayers();
5043 }
5044 }
chaviwa76b2712017-09-20 12:02:26 -07005045
chaviwa76b2712017-09-20 12:02:26 -07005046 private:
chaviw7206d492017-11-10 16:16:12 -08005047 const sp<Layer> mLayer;
5048 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005049
Peiyong Linefefaac2018-08-17 12:27:51 -07005050 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005051 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005052
5053 SurfaceFlinger* mFlinger;
5054 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005055 };
5056
Robert Carrc0df3122019-04-11 13:18:21 -07005057 int reqWidth = 0;
5058 int reqHeight = 0;
5059 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005060 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005061 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005062
Robert Carrc0df3122019-04-11 13:18:21 -07005063 {
5064 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005065
Robert Carrc0df3122019-04-11 13:18:21 -07005066 parent = fromHandle(layerHandleBinder);
5067 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5068 ALOGE("captureLayers called with an invalid or removed parent");
5069 return NAME_NOT_FOUND;
5070 }
5071
5072 const int uid = IPCThreadState::self()->getCallingUid();
5073 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5074 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5075 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5076 return PERMISSION_DENIED;
5077 }
5078
5079 if (sourceCrop.width() <= 0) {
5080 crop.left = 0;
5081 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5082 }
5083
5084 if (sourceCrop.height() <= 0) {
5085 crop.top = 0;
5086 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5087 }
5088 reqWidth = crop.width() * frameScale;
5089 reqHeight = crop.height() * frameScale;
5090
5091 for (const auto& handle : excludeHandles) {
5092 sp<Layer> excludeLayer = fromHandle(handle);
5093 if (excludeLayer != nullptr) {
5094 excludeLayers.emplace(excludeLayer);
5095 } else {
5096 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5097 return NAME_NOT_FOUND;
5098 }
5099 }
5100 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005101
Chia-I Wu20261cb2018-08-23 12:55:44 -07005102 // really small crop or frameScale
5103 if (reqWidth <= 0) {
5104 reqWidth = 1;
5105 }
5106 if (reqHeight <= 0) {
5107 reqHeight = 1;
5108 }
5109
Robert Carr866455f2019-04-02 16:28:26 -07005110 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5111 auto traverseLayers = [parent, childrenOnly,
5112 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005113 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5114 if (!layer->isVisible()) {
5115 return;
Robert Carr578038f2018-03-09 12:25:24 -08005116 } else if (childrenOnly && layer == parent.get()) {
5117 return;
chaviwa76b2712017-09-20 12:02:26 -07005118 }
Robert Carr866455f2019-04-02 16:28:26 -07005119
5120 sp<Layer> p = layer;
5121 while (p != nullptr) {
5122 if (excludeLayers.count(p) != 0) {
5123 return;
5124 }
5125 p = p->getParent();
5126 }
5127
chaviwa76b2712017-09-20 12:02:26 -07005128 visitor(layer);
5129 });
5130 };
Robert Carr108b2c72019-04-02 16:32:58 -07005131
5132 bool outCapturedSecureLayers = false;
5133 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5134 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005135}
5136
5137status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5138 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005139 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005140 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005141 bool useIdentityTransform,
5142 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005143 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005144
Peiyong Lin0e003c92018-09-17 11:09:51 -07005145 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005146 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5147 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005148 *outBuffer =
5149 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5150 static_cast<android_pixel_format>(reqPixelFormat), 1,
5151 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005152
Robert Carr108b2c72019-04-02 16:32:58 -07005153 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5154 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005155}
5156
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005157status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5158 TraverseLayersFunction traverseLayers,
5159 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005160 bool useIdentityTransform,
5161 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005162 // This mutex protects syncFd and captureResult for communication of the return values from the
5163 // main thread back to this Binder thread
5164 std::mutex captureMutex;
5165 std::condition_variable captureCondition;
5166 std::unique_lock<std::mutex> captureLock(captureMutex);
5167 int syncFd = -1;
5168 std::optional<status_t> captureResult;
5169
Robert Carr03480e22018-01-04 16:02:06 -08005170 const int uid = IPCThreadState::self()->getCallingUid();
5171 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5172
Dominik Laskowski8c001672018-05-30 16:52:06 -07005173 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005174 // If there is a refresh pending, bug out early and tell the binder thread to try again
5175 // after the refresh.
5176 if (mRefreshPending) {
5177 ATRACE_NAME("Skipping screenshot for now");
5178 std::unique_lock<std::mutex> captureLock(captureMutex);
5179 captureResult = std::make_optional<status_t>(EAGAIN);
5180 captureCondition.notify_one();
5181 return;
5182 }
5183
5184 status_t result = NO_ERROR;
5185 int fd = -1;
5186 {
5187 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005188 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005189 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005190 useIdentityTransform, forSystem, &fd,
5191 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005192 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193 }
5194
5195 {
5196 std::unique_lock<std::mutex> captureLock(captureMutex);
5197 syncFd = fd;
5198 captureResult = std::make_optional<status_t>(result);
5199 captureCondition.notify_one();
5200 }
5201 });
5202
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005203 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005204 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005205 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005206 while (*captureResult == EAGAIN) {
5207 captureResult.reset();
5208 result = postMessageAsync(message);
5209 if (result != NO_ERROR) {
5210 return result;
5211 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005212 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005213 }
5214 result = *captureResult;
5215 }
5216
5217 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005218 sync_wait(syncFd, -1);
5219 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005220 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005221
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005222 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005223}
5224
chaviwa76b2712017-09-20 12:02:26 -07005225void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005226 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005227 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5228 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005229 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005230
chaviwa76b2712017-09-20 12:02:26 -07005231 const auto reqWidth = renderArea.getReqWidth();
5232 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005233 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005234 const auto transform = renderArea.getTransform();
5235 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005236
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005237 renderengine::DisplaySettings clientCompositionDisplay;
5238 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005239
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005240 // assume that bounds are never offset, and that they are the same as the
5241 // buffer bounds.
5242 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005243 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005244 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005245
5246 // Now take into account the rotation flag. We append a transform that
5247 // rotates the layer stack about the origin, then translate by buffer
5248 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005249 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005250 int displacementX = 0;
5251 int displacementY = 0;
5252 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5253 switch (rotation) {
5254 case ui::Transform::ROT_90:
5255 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005256 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005257 break;
5258 case ui::Transform::ROT_180:
5259 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005260 displacementY = renderArea.getBounds().getWidth();
5261 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005262 break;
5263 case ui::Transform::ROT_270:
5264 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005265 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005266 break;
5267 default:
5268 break;
5269 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005270
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005271 // We need to transform the clipping window into the right spot.
5272 // First, rotate the clipping rectangle by the rotation hint to get the
5273 // right orientation
5274 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5275 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5276 const vec4 rotClipTL = rotMatrix * clipTL;
5277 const vec4 rotClipBR = rotMatrix * clipBR;
5278 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5279 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5280 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5281 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5282
5283 // Now reposition the clipping rectangle with the displacement vector
5284 // computed above.
5285 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005286 clientCompositionDisplay.clip =
5287 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5288 newClipRight + displacementX, newClipBottom + displacementY);
5289
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005290 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005291 clientCompositionDisplay.globalTransform =
5292 clipTransform * clientCompositionDisplay.globalTransform;
5293
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005294 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5295 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005296
chaviw50da5042018-04-09 13:49:37 -07005297 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005298
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005299 renderengine::LayerSettings fillLayer;
5300 fillLayer.source.buffer.buffer = nullptr;
5301 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5302 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5303 fillLayer.alpha = half(alpha);
5304 clientCompositionLayers.push_back(fillLayer);
5305
5306 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005307 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005308 const bool supportProtectedContent = false;
5309 Region clip(renderArea.getBounds());
5310 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5311 clip,
5312 useIdentityTransform,
5313 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5314 renderArea.isSecure(),
5315 supportProtectedContent,
5316 clearRegion,
5317 };
5318 auto result = layer->prepareClientComposition(targetSettings);
5319 if (result) {
5320 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005321 }
chaviwa76b2712017-09-20 12:02:26 -07005322 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005323
5324 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005325 // Use an empty fence for the buffer fence, since we just created the buffer so
5326 // there is no need for synchronization with the GPU.
5327 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005328 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005329 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005330 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005331 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005332
5333 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005334}
5335
chaviwa76b2712017-09-20 12:02:26 -07005336status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5337 TraverseLayersFunction traverseLayers,
5338 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005339 bool useIdentityTransform, bool forSystem,
5340 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005341 ATRACE_CALL();
5342
chaviwa76b2712017-09-20 12:02:26 -07005343 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005344 outCapturedSecureLayers =
5345 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005346 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005347
Robert Carr03480e22018-01-04 16:02:06 -08005348 // We allow the system server to take screenshots of secure layers for
5349 // use in situations like the Screen-rotation animation and place
5350 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005351 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005352 ALOGW("FB is protected: PERMISSION_DENIED");
5353 return PERMISSION_DENIED;
5354 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005355 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005356 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005357}
5358
chaviw95ef3c42019-02-14 10:55:09 -08005359void SurfaceFlinger::setInputWindowsFinished() {
5360 Mutex::Autolock _l(mStateLock);
5361
5362 mPendingSyncInputWindows = false;
5363 mTransactionCV.broadcast();
5364}
chaviw5f21a5e2019-02-14 10:00:34 -08005365
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005366// ---------------------------------------------------------------------------
5367
Dan Stoza412903f2017-04-27 13:42:17 -07005368void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5369 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005370}
5371
Dan Stoza412903f2017-04-27 13:42:17 -07005372void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5373 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005374}
5375
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005376void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005377 const LayerVector::Visitor& visitor) {
5378 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005379 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005380 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005381 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005382 continue;
5383 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005384 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005385 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005386 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005387 return;
5388 }
chaviwa76b2712017-09-20 12:02:26 -07005389 if (!layer->isVisible()) {
5390 return;
5391 }
5392 visitor(layer);
5393 });
5394 }
5395}
5396
Dominik Laskowski22488f62019-03-28 09:53:04 -07005397void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5398 const std::vector<int32_t>& allowedConfigs) {
5399 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005400 return;
5401 }
5402
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005403 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5404 allowedConfigs.end());
5405 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5406 return;
5407 }
5408
Ady Abraham838de062019-02-04 10:24:03 -08005409 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005410 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5411
5412 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5413 // that listeners that care about a change in allowed configs can get the notification.
5414 // Giving current ActiveConfig so that most other listeners would just drop the event
5415 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5416 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005417
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005418 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5419 const auto& type = mScheduler->getPreferredRefreshRateType();
5420 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5421 if (isDisplayConfigAllowed(config.configId)) {
5422 ALOGV("switching to Scheduler preferred config %d", config.configId);
5423 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5424 } else {
5425 // Set the highest allowed config by iterating backwards on available refresh rates
5426 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5427 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5428 if (isDisplayConfigAllowed(iter->second.configId)) {
5429 ALOGV("switching to allowed config %d", iter->second.configId);
5430 setDesiredActiveConfig(
5431 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5432 break;
5433 }
5434 }
5435 }
5436 } else if (!allowedConfigs.empty()) {
5437 ALOGV("switching to config %d", allowedConfigs[0]);
5438 setDesiredActiveConfig(
5439 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5440 }
Ady Abraham838de062019-02-04 10:24:03 -08005441}
5442
Dominik Laskowski22488f62019-03-28 09:53:04 -07005443status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005444 const std::vector<int32_t>& allowedConfigs) {
5445 ATRACE_CALL();
5446
Dominik Laskowski22488f62019-03-28 09:53:04 -07005447 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005448 return BAD_VALUE;
5449 }
5450
Ady Abraham34392f72019-04-10 11:29:27 -07005451 if (mDebugDisplayConfigSetByBackdoor) {
5452 // ignore this request as config is overridden by backdoor
5453 return NO_ERROR;
5454 }
5455
Ady Abraham838de062019-02-04 10:24:03 -08005456 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005457 const auto display = getDisplayDeviceLocked(displayToken);
5458 if (!display) {
5459 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5460 displayToken.get());
5461 } else if (display->isVirtual()) {
5462 ALOGW("Attempt to set allowed display configs for virtual display");
5463 } else {
5464 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5465 }
Ady Abraham838de062019-02-04 10:24:03 -08005466 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005467
Ady Abraham838de062019-02-04 10:24:03 -08005468 return NO_ERROR;
5469}
5470
Dominik Laskowski22488f62019-03-28 09:53:04 -07005471status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005472 std::vector<int32_t>* outAllowedConfigs) {
5473 ATRACE_CALL();
5474
Dominik Laskowski22488f62019-03-28 09:53:04 -07005475 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005476 return BAD_VALUE;
5477 }
5478
Dominik Laskowski22488f62019-03-28 09:53:04 -07005479 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005480
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005481 const auto display = getDisplayDeviceLocked(displayToken);
5482 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005483 return NAME_NOT_FOUND;
5484 }
5485
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005486 if (display->isPrimary()) {
5487 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5488 }
5489
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005490 return NO_ERROR;
5491}
5492
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005493void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005494 mFlinger->setInputWindowsFinished();
5495}
5496
Robert Carrc0df3122019-04-11 13:18:21 -07005497sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5498 BBinder *b = handle->localBinder();
5499 if (b == nullptr) {
5500 return nullptr;
5501 }
5502 auto it = mLayersByLocalBinderToken.find(b);
5503 if (it != mLayersByLocalBinderToken.end()) {
5504 return it->second.promote();
5505 }
5506 return nullptr;
5507}
5508
Alec Mouri4545a8a2019-08-08 20:05:32 -07005509void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5510 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5511}
5512
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005513} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005514
Mathias Agopian3f844832013-08-07 21:24:32 -07005515#if defined(__gl_h_)
5516#error "don't include gl/gl.h in this file"
5517#endif
5518
5519#if defined(__gl2_h_)
5520#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005521#endif