blob: 3a0a86c4d89b4513a7539a8400dcfe26e780ca63 [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
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700125using namespace std::string_literals;
126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700166ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
167 switch (rotation) {
168 case ISurfaceComposer::eRotateNone:
169 return ui::Transform::ROT_0;
170 case ISurfaceComposer::eRotate90:
171 return ui::Transform::ROT_90;
172 case ISurfaceComposer::eRotate180:
173 return ui::Transform::ROT_180;
174 case ISurfaceComposer::eRotate270:
175 return ui::Transform::ROT_270;
176 }
177 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
178 return ui::Transform::ROT_0;
179}
180
Peiyong Linfca547f2018-07-09 13:03:33 -0700181#pragma clang diagnostic pop
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183class ConditionalLock {
184public:
185 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
186 if (lock) {
187 mMutex.lock();
188 }
189 }
190 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
191private:
192 Mutex& mMutex;
193 bool mLocked;
194};
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
Peiyong Lin9d846a52018-11-05 13:18:20 -0800196// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
197bool validateCompositionDataspace(Dataspace dataspace) {
198 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
199}
200
Steven Thomasb02664d2017-07-26 18:48:28 -0700201} // namespace anonymous
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203// ---------------------------------------------------------------------------
204
Mathias Agopian99b49842011-06-27 16:05:52 -0700205const String16 sHardwareTest("android.permission.HARDWARE_TEST");
206const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
207const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
208const String16 sDump("android.permission.DUMP");
209
210// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800213uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800214bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800215bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800216int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600217bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700218int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700219bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700220bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700221Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
223Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700225
Kalle Raitaa099a242017-01-11 11:17:29 -0800226std::string getHwcServiceName() {
227 char value[PROPERTY_VALUE_MAX] = {};
228 property_get("debug.sf.hwc_service_name", value, "default");
229 ALOGI("Using HWComposer service: '%s'", value);
230 return std::string(value);
231}
232
233bool useTrebleTestingOverride() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.treble_testing_override", value, "false");
236 ALOGI("Treble testing override: '%s'", value);
237 return std::string(value) == "true";
238}
239
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
241 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Enhanced");
248 default:
249 return std::string("Unknown ") +
250 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252}
253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
257 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700259 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700260 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700261 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700262 mCompositionEngine(mFactory.createCompositionEngine()),
Valerie Haud251afb2019-03-29 14:19:02 -0700263 mPhaseOffsets(mFactory.createPhaseOffsets()),
264 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800265
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700266SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800267 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800276
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 mDefaultCompositionDataspace =
287 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700288 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
289 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 defaultCompositionDataspace = mDefaultCompositionDataspace;
291 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
292 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
293 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
294 wideColorGamutCompositionPixelFormat =
295 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700296
Yichi Chenda901bf2019-06-28 14:58:27 +0800297 mColorSpaceAgnosticDataspace =
298 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
303 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
304 switch (tmpPrimaryDisplayOrientation) {
305 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700315 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
317 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Sundong Ahn85131bd2019-02-18 15:51:53 +0900320 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 // debugging stuff...
323 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700324
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700326 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 property_get("debug.sf.showupdates", value, "0");
329 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700331 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000332
333 // DDMS debugging deprecated (b/120782499)
334 property_get("debug.sf.ddms", value, "0");
335 int debugDdms = atoi(value);
336 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700337
338 property_get("debug.sf.disable_backpressure", value, "0");
339 mPropagateBackpressure = !atoi(value);
340 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700341
Ady Abrahamadb9a992019-09-19 21:21:55 +0000342 property_get("debug.sf.enable_gl_backpressure", value, "0");
343 mPropagateBackpressureClientComposition = atoi(value);
344 ALOGI_IF(mPropagateBackpressureClientComposition,
345 "Enabling backpressure propagation for Client Composition");
346
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800347 property_get("debug.sf.enable_hwc_vds", value, "0");
348 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800349 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800350
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800351 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800352 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800353 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700354
Yiwei Zhang243b3782018-05-15 17:40:04 -0700355 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700356 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
357 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
358
Dan Stozaec460082018-12-17 15:35:09 -0800359 property_get("debug.sf.luma_sampling", value, "1");
360 mLumaSampling = atoi(value);
361
Romain Guy11d63f42017-07-20 12:47:14 -0700362 // We should be reading 'persist.sys.sf.color_saturation' here
363 // but since /data may be encrypted, we need to wait until after vold
364 // comes online to attempt to read the property. The property is
365 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800366
367 if (useTrebleTestingOverride()) {
368 // Without the override SurfaceFlinger cannot connect to HIDL
369 // services that are not listed in the manifests. Considered
370 // deriving the setting from the set service name, but it
371 // would be brittle if the name that's not 'default' is used
372 // for production purposes later on.
373 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375}
376
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800377void SurfaceFlinger::onFirstRef()
378{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800379 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800380}
381
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700382SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383
Dan Stozac7014012014-02-14 15:03:43 -0800384void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385{
386 // the window manager died on us. prepare its eulogy.
387
Andy McFadden13a082e2012-08-24 10:16:42 -0700388 // restore initial conditions (default device unblank, etc)
389 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390
391 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700392 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800393}
394
Robert Carr1db73f62016-12-21 12:58:51 -0800395static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700396 status_t err = client->initCheck();
397 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800398 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 }
Robert Carr1db73f62016-12-21 12:58:51 -0800400 return nullptr;
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
404 return initClient(new Client(this));
405}
406
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700407sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
408 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700409{
410 class DisplayToken : public BBinder {
411 sp<SurfaceFlinger> flinger;
412 virtual ~DisplayToken() {
413 // no more references, this display must be terminated
414 Mutex::Autolock _l(flinger->mStateLock);
415 flinger->mCurrentState.displays.removeItem(this);
416 flinger->setTransactionFlags(eDisplayTransactionNeeded);
417 }
418 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700419 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700420 : flinger(flinger) {
421 }
422 };
423
424 sp<BBinder> token = new DisplayToken(this);
425
426 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700427 // Display ID is assigned when virtual display is allocated by HWC.
428 DisplayDeviceState state;
429 state.isSecure = secure;
430 state.displayName = displayName;
431 mCurrentState.displays.add(token, state);
432 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433 return token;
434}
435
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700436void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700437 Mutex::Autolock _l(mStateLock);
438
Dominik Laskowski075d3172018-05-24 15:50:06 -0700439 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
440 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700441 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 return;
443 }
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
446 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 ALOGE("destroyDisplay called for non-virtual display");
448 return;
449 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 mInterceptor->saveDisplayDeletion(state.sequenceId);
451 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 setTransactionFlags(eDisplayTransactionNeeded);
453}
454
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800455std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
456 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800458 const auto internalDisplayId = getInternalDisplayIdLocked();
459 if (!internalDisplayId) {
460 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700461 }
462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463 std::vector<PhysicalDisplayId> displayIds;
464 displayIds.reserve(mPhysicalDisplayTokens.size());
465 displayIds.push_back(internalDisplayId->value);
466
467 for (const auto& [id, token] : mPhysicalDisplayTokens) {
468 if (id != *internalDisplayId) {
469 displayIds.push_back(id.value);
470 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473 return displayIds;
474}
475
476sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
477 Mutex::Autolock lock(mStateLock);
478 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479}
480
Ady Abraham37965d42018-11-01 13:43:32 -0700481status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
482 if (!outGetColorManagement) {
483 return BAD_VALUE;
484 }
485 *outGetColorManagement = useColorManagement;
486 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700487}
488
Lloyd Pique441d5042018-10-18 16:49:51 -0700489HWComposer& SurfaceFlinger::getHwComposer() const {
490 return mCompositionEngine->getHwComposer();
491}
492
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700493renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
494 return mCompositionEngine->getRenderEngine();
495}
496
Lloyd Pique70d91362018-10-18 16:02:55 -0700497compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
498 return *mCompositionEngine.get();
499}
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501void SurfaceFlinger::bootFinished()
502{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700503 if (mStartPropertySetThread->join() != NO_ERROR) {
504 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 const nsecs_t now = systemTime();
507 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000508 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700509
Mikael Pessa90092f42019-08-26 17:22:04 -0700510 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700511
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512 // wait patiently for the window manager death
513 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700514 mWindowManager = defaultServiceManager()->getService(name);
515 if (mWindowManager != 0) {
516 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 }
Robert Carr720e5062018-07-30 17:45:14 -0700518 sp<IBinder> input(defaultServiceManager()->getService(
519 String16("inputflinger")));
520 if (input == nullptr) {
521 ALOGE("Failed to link to input service");
522 } else {
523 mInputFlinger = interface_cast<IInputFlinger>(input);
524 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525
Steven Thomas050b2c82017-03-06 11:45:16 -0800526 if (mVrFlinger) {
527 mVrFlinger->OnBootFinished();
528 }
529
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700531 // formerly we would just kill the process, but we now ask it to exit so it
532 // can choose where to stop the animation.
533 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700534
535 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
536 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
537 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700538
Ana Krulecbd6654b2019-02-15 15:18:15 -0800539 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800540 readPersistentProperties();
541 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800542
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700543 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
544 // set the refresh rate according to the policy
545 const auto& performanceRefreshRate =
546 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800547
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700548 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
549 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
550 } else {
551 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
552 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800553 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800554 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555}
556
Dan Stoza436ccf32018-06-21 12:10:12 -0700557uint32_t SurfaceFlinger::getNewTexture() {
558 {
559 std::lock_guard lock(mTexturePoolMutex);
560 if (!mTexturePool.empty()) {
561 uint32_t name = mTexturePool.back();
562 mTexturePool.pop_back();
563 ATRACE_INT("TexturePoolSize", mTexturePool.size());
564 return name;
565 }
566
567 // The pool was too small, so increase it for the future
568 ++mTexturePoolSize;
569 }
570
571 // The pool was empty, so we need to get a new texture name directly using a
572 // blocking call to the main thread
573 uint32_t name = 0;
574 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
575 return name;
576}
577
Mathias Agopian3f844832013-08-07 21:24:32 -0700578void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700579 std::lock_guard lock(mTexturePoolMutex);
580 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
581 // to actually delete this or not based on mTexturePoolSize
582 mTexturePool.push_back(texture);
583 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700584}
585
Wei Wangf9b05ee2017-07-19 20:59:39 -0700586// Do not call property_set on main thread which will be blocked by init
587// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700589 ALOGI( "SurfaceFlinger's main thread ready to run. "
590 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700591 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900592
Steven Thomasb02664d2017-07-26 18:48:28 -0700593 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700596 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800597 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700598 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
599 renderengine::RenderEngineCreationArgs::Builder()
600 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
601 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
602 .setUseColorManagerment(useColorManagement)
603 .setEnableProtectedContext(enable_protected_contents(false))
604 .setPrecacheToneMapperShaderOnly(false)
605 .setContextPriority(useContextPriority
606 ? renderengine::RenderEngine::ContextPriority::HIGH
607 : renderengine::RenderEngine::ContextPriority::MEDIUM)
608 .build()));
Steven Thomasb02664d2017-07-26 18:48:28 -0700609
610 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
611 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700612 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
613 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800614 // Process any initial hotplug and resulting display changes.
615 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700616 const auto display = getDefaultDisplayDeviceLocked();
617 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700618 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700619 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800620
Steven Thomas050b2c82017-03-06 11:45:16 -0800621 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700622 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700623 // This callback is called from the vr flinger dispatch thread. We
624 // need to call signalTransaction(), which requires holding
625 // mStateLock when we're not on the main thread. Acquiring
626 // mStateLock from the vr flinger dispatch thread might trigger a
627 // deadlock in surface flinger (see b/66916578), so post a message
628 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700629 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700630 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
631 mVrFlingerRequestsDisplay = requestDisplay;
632 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700633 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700635 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
636 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700637 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700638 .value_or(0),
639 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 if (!mVrFlinger) {
641 ALOGE("Failed to start vrflinger");
642 }
643 }
644
Mathias Agopian92a979a2012-08-02 18:32:23 -0700645 // initialize our drawing state
646 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700647
Andy McFadden13a082e2012-08-24 10:16:42 -0700648 // set initial conditions (e.g. unblank default device)
649 initializeDisplays();
650
Steven Thomas137d4bc2019-07-25 16:55:14 -0700651 char primeShaderCache[PROPERTY_VALUE_MAX];
652 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
653 if (atoi(primeShaderCache)) {
654 getRenderEngine().primeCache();
655 }
Dan Stoza4e637772016-07-28 13:31:51 -0700656
Wei Wangf9b05ee2017-07-19 20:59:39 -0700657 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700658
659 const bool presentFenceReliable =
660 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
661 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700662
663 if (mStartPropertySetThread->Start() != NO_ERROR) {
664 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700668}
669
Romain Guy11d63f42017-07-20 12:47:14 -0700670void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700671 Mutex::Autolock _l(mStateLock);
672
Romain Guy11d63f42017-07-20 12:47:14 -0700673 char value[PROPERTY_VALUE_MAX];
674
675 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800676 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700677 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800678 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100679
680 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700681 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800682
683 property_get("persist.sys.sf.color_mode", value, "0");
684 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700685}
686
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800688 // Start boot animation service by setting a property mailbox
689 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800691 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 if (mStartPropertySetThread->join() != NO_ERROR) {
693 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800694 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695}
696
Mathias Agopian875d8e12013-06-07 15:35:48 -0700697size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700698 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700699}
700
Mathias Agopian875d8e12013-06-07 15:35:48 -0700701size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700702 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700703}
704
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800706
Jamie Gennis582270d2011-08-17 18:19:00 -0700707bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800708 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800709 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800710 return authenticateSurfaceTextureLocked(bufferProducer);
711}
712
713bool SurfaceFlinger::authenticateSurfaceTextureLocked(
714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800715 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800716 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800717}
718
Brian Anderson6b376712017-04-04 10:51:39 -0700719status_t SurfaceFlinger::getSupportedFrameTimestamps(
720 std::vector<FrameEvent>* outSupported) const {
721 *outSupported = {
722 FrameEvent::REQUESTED_PRESENT,
723 FrameEvent::ACQUIRE,
724 FrameEvent::LATCH,
725 FrameEvent::FIRST_REFRESH_START,
726 FrameEvent::LAST_REFRESH_START,
727 FrameEvent::GPU_COMPOSITION_DONE,
728 FrameEvent::DEQUEUE_READY,
729 FrameEvent::RELEASE,
730 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700731 ConditionalLock _l(mStateLock,
732 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700733 if (!getHwComposer().hasCapability(
734 HWC2::Capability::PresentFenceIsNotReliable)) {
735 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
736 }
737 return NO_ERROR;
738}
739
Dominik Laskowski22488f62019-03-28 09:53:04 -0700740status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
741 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700742 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700743 return BAD_VALUE;
744 }
745
Dominik Laskowski22488f62019-03-28 09:53:04 -0700746 Mutex::Autolock lock(mStateLock);
747
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800748 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700749 if (!displayId) {
750 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700751 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753 // TODO: Not sure if display density should handled by SF any longer
754 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700755 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700757 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800758 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700759 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 }
761 return density;
762 }
763 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700764 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700765 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700766 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700767 return getDensityFromProperty("ro.sf.lcd_density"); }
768 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700769
Dan Stoza7f7da322014-05-02 15:26:25 -0700770 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700771
Dominik Laskowski075d3172018-05-24 15:50:06 -0700772 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 DisplayInfo info = DisplayInfo();
774
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 float xdpi = hwConfig->getDpiX();
776 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700777
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700778 info.w = hwConfig->getWidth();
779 info.h = hwConfig->getHeight();
780 // Default display viewport to display width and height
781 info.viewportW = info.w;
782 info.viewportH = info.h;
783
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800784 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700785 // The density of the device is provided by a build property
786 float density = Density::getBuildDensity() / 160.0f;
787 if (density == 0) {
788 // the build doesn't provide a density -- this is wrong!
789 // use xdpi instead
790 ALOGE("ro.sf.lcd_density must be defined as a build property");
791 density = xdpi / 160.0f;
792 }
793 if (Density::getEmuDensity()) {
794 // if "qemu.sf.lcd_density" is specified, it overrides everything
795 xdpi = ydpi = density = Density::getEmuDensity();
796 density /= 160.0f;
797 }
798 info.density = density;
799
800 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700801 const auto display = getDefaultDisplayDeviceLocked();
802 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700803
804 // This is for screenrecord
805 const Rect viewport = display->getViewport();
806 if (viewport.isValid()) {
807 info.viewportW = uint32_t(viewport.getWidth());
808 info.viewportH = uint32_t(viewport.getHeight());
809 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700810 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 } else {
812 // TODO: where should this value come from?
813 static const int TV_DENSITY = 213;
814 info.density = TV_DENSITY / 160.0f;
815 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700816
817 const auto display = getDisplayDeviceLocked(displayToken);
818 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 }
820
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 info.xdpi = xdpi;
822 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700824 const auto refreshRateType =
825 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700826 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
827 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828
Andy McFadden91b2ca82014-06-13 14:04:23 -0700829 // This is how far in advance a buffer must be queued for
830 // presentation at a given time. If you want a buffer to appear
831 // on the screen at time N, you must submit the buffer before
832 // (N - presentationDeadline).
833 //
834 // Normally it's one full refresh period (to give SF a chance to
835 // latch the buffer), but this can be reduced by configuring a
836 // DispSync offset. Any additional delays introduced by the hardware
837 // composer or panel must be accounted for here.
838 //
839 // We add an additional 1ms to allow for processing time and
840 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700841 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700842
843 // All non-virtual displays are currently considered secure.
844 info.secure = true;
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700847 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800848 std::swap(info.w, info.h);
849 }
850
Michael Wright28f24d02016-07-12 13:30:53 -0700851 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852 }
853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 return NO_ERROR;
855}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700856
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700857status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
858 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700859 return BAD_VALUE;
860 }
861
Ana Krulecc2870422019-01-29 19:00:58 -0800862 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700863 return NO_ERROR;
864}
865
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700866int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
867 const auto display = getDisplayDevice(displayToken);
868 if (!display) {
869 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800870 return BAD_VALUE;
871 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700872
Steven Thomasc9098452019-09-30 17:15:05 -0700873 if (display->isPrimary()) {
874 std::lock_guard<std::mutex> lock(mActiveConfigLock);
875 if (mDesiredActiveConfigChanged) {
876 return mDesiredActiveConfig.configId;
877 } else {
878 return display->getActiveConfig();
879 }
880 } else {
881 return display->getActiveConfig();
882 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700883}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700884
Ady Abraham03b02dd2019-03-21 15:40:11 -0700885void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800886 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800887
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800888 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800889 // config twice. However event generation config might have changed so we need to update it
890 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800891 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700892 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
893 mDesiredActiveConfig = info;
894 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800895
896 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800897 // This will trigger HWC refresh without resetting the idle timer.
898 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700899 // Start receiving vsync samples now, so that we can detect a period
900 // switch.
901 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700902 // As we called to set period, we will call to onRefreshRateChangeCompleted once
903 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700904 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700905 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700906 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800907 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800908 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700909
910 if (mRefreshRateOverlay) {
911 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
912 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800913}
914
915status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
916 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800917
918 std::vector<int32_t> allowedConfig;
919 allowedConfig.push_back(mode);
920
921 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922}
923
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800924void SurfaceFlinger::setActiveConfigInternal() {
925 ATRACE_CALL();
926
Dominik Laskowski22488f62019-03-28 09:53:04 -0700927 const auto display = getDefaultDisplayDeviceLocked();
928 if (!display) {
929 return;
930 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800931
Dominik Laskowski22488f62019-03-28 09:53:04 -0700932 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700933 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
934 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700935
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 display->setActiveConfig(mUpcomingActiveConfig.configId);
937
Alec Mouri754c98a2019-03-18 18:53:42 -0700938 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700939 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700941
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800942 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800943 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
944 mUpcomingActiveConfig.configId);
945 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946}
947
Ady Abraham53852a52019-05-28 18:07:44 -0700948void SurfaceFlinger::desiredActiveConfigChangeDone() {
949 std::lock_guard<std::mutex> lock(mActiveConfigLock);
950 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
951 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700952
953 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
954 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700955 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700956}
957
Dominik Laskowski22488f62019-03-28 09:53:04 -0700958bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800959 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800960 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700961 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700963 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800964 return true;
965 }
966
967 // We received the present fence from the HWC, so we assume it successfully updated
968 // the config, hence we update SF.
969 mCheckPendingFence = false;
970 setActiveConfigInternal();
971 }
972
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973 // Store the local variable to release the lock.
974 ActiveConfigInfo desiredActiveConfig;
975 {
976 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800977 if (!mDesiredActiveConfigChanged) {
978 return false;
979 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980 desiredActiveConfig = mDesiredActiveConfig;
981 }
982
Dominik Laskowski22488f62019-03-28 09:53:04 -0700983 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800984 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
985 // display is not valid or we are already in the requested mode
986 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700987 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800988 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800990
Ady Abraham838de062019-02-04 10:24:03 -0800991 // Desired active config was set, it is different than the config currently in use, however
992 // allowed configs might have change by the time we process the refresh.
993 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -0700994 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -0700995 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -0800996 return false;
997 }
Alec Mouri7f015182019-07-11 13:56:22 -0700998
Ady Abrahamb838aed2019-02-12 15:30:16 -0800999 mUpcomingActiveConfig = desiredActiveConfig;
1000 const auto displayId = display->getId();
1001 LOG_ALWAYS_FATAL_IF(!displayId);
1002
1003 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1004 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1005
1006 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001008 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001010}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1013 Vector<ColorMode>* outColorModes) {
1014 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001015 return BAD_VALUE;
1016 }
1017
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001019 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001020 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001021 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1022
1023 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1024 if (!displayId) {
1025 return NAME_NOT_FOUND;
1026 }
1027
Dominik Laskowski075d3172018-05-24 15:50:06 -07001028 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001029 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001030 }
Michael Wright28f24d02016-07-12 13:30:53 -07001031 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001032
1033 // If it's built-in display and the configuration claims it's not wide color capable,
1034 // filter out all wide color modes. The typical reason why this happens is that the
1035 // hardware is not good enough to support GPU composition of wide color, and thus the
1036 // OEMs choose to disable this capability.
1037 if (isInternalDisplay && !hasWideColorDisplay) {
1038 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1039 isWideColorMode);
1040 } else {
1041 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1042 }
Michael Wright28f24d02016-07-12 13:30:53 -07001043
1044 return NO_ERROR;
1045}
1046
Daniel Solomon42d04562019-01-20 21:03:19 -08001047status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1048 ui::DisplayPrimaries &primaries) {
1049 if (!displayToken) {
1050 return BAD_VALUE;
1051 }
1052
1053 // Currently we only support this API for a single internal display.
1054 if (getInternalDisplayToken() != displayToken) {
1055 return BAD_VALUE;
1056 }
1057
1058 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1059 return NO_ERROR;
1060}
1061
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1063 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001064 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001065 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001067}
1068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001070 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071 Vector<ColorMode> modes;
1072 getDisplayColorModes(displayToken, &modes);
1073 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1074 if (mode < ColorMode::NATIVE || !exists) {
1075 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1076 decodeColorMode(mode).c_str(), mode, displayToken.get());
1077 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001078 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079 const auto display = getDisplayDevice(displayToken);
1080 if (!display) {
1081 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1082 decodeColorMode(mode).c_str(), mode, displayToken.get());
1083 } else if (display->isVirtual()) {
1084 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1085 decodeColorMode(mode).c_str(), mode);
1086 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001087 display->getCompositionDisplay()->setColorProfile(
1088 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1089 RenderIntent::COLORIMETRIC,
1090 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091 }
1092 }));
1093
Michael Wright28f24d02016-07-12 13:30:53 -07001094 return NO_ERROR;
1095}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001096
Svetoslavd85084b2014-03-20 10:28:31 -07001097status_t SurfaceFlinger::clearAnimationFrameStats() {
1098 Mutex::Autolock _l(mStateLock);
1099 mAnimFrameTracker.clearStats();
1100 return NO_ERROR;
1101}
1102
1103status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1104 Mutex::Autolock _l(mStateLock);
1105 mAnimFrameTracker.getStats(outStats);
1106 return NO_ERROR;
1107}
1108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1110 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001111 Mutex::Autolock _l(mStateLock);
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113 const auto display = getDisplayDeviceLocked(displayToken);
1114 if (!display) {
1115 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001116 return BAD_VALUE;
1117 }
1118
Peiyong Linfb069302018-04-25 14:34:31 -07001119 // At this point the DisplayDeivce should already be set up,
1120 // meaning the luminance information is already queried from
1121 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001123 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1124 capabilities.getDesiredMaxLuminance(),
1125 capabilities.getDesiredMaxAverageLuminance(),
1126 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001127
1128 return NO_ERROR;
1129}
1130
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001131status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1132 ui::PixelFormat* outFormat,
1133 ui::Dataspace* outDataspace,
1134 uint8_t* outComponentMask) const {
1135 if (!outFormat || !outDataspace || !outComponentMask) {
1136 return BAD_VALUE;
1137 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001138 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001139 if (!display || !display->getId()) {
1140 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1141 return BAD_VALUE;
1142 }
1143 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1144 outDataspace, outComponentMask);
1145}
1146
Kevin DuBois74e53772018-11-19 10:52:38 -08001147status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1148 bool enable, uint8_t componentMask,
1149 uint64_t maxFrames) const {
1150 const auto display = getDisplayDevice(displayToken);
1151 if (!display || !display->getId()) {
1152 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1153 return BAD_VALUE;
1154 }
1155
1156 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1157 componentMask, maxFrames);
1158}
1159
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001160status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1161 uint64_t maxFrames, uint64_t timestamp,
1162 DisplayedFrameStats* outStats) const {
1163 const auto display = getDisplayDevice(displayToken);
1164 if (!display || !display->getId()) {
1165 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1166 return BAD_VALUE;
1167 }
1168
1169 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1170 outStats);
1171}
1172
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001173status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1174 if (!outSupported) {
1175 return BAD_VALUE;
1176 }
1177 *outSupported = getRenderEngine().supportsProtectedContent();
1178 return NO_ERROR;
1179}
1180
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001181status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1182 bool* outIsWideColorDisplay) const {
1183 if (!displayToken || !outIsWideColorDisplay) {
1184 return BAD_VALUE;
1185 }
1186 Mutex::Autolock _l(mStateLock);
1187 const auto display = getDisplayDeviceLocked(displayToken);
1188 if (!display) {
1189 return BAD_VALUE;
1190 }
Peiyong Linff84a152019-05-17 18:36:19 -07001191
1192 // Use hasWideColorDisplay to override built-in display.
1193 const auto displayId = display->getId();
1194 if (displayId && displayId == getInternalDisplayIdLocked()) {
1195 *outIsWideColorDisplay = hasWideColorDisplay;
1196 return NO_ERROR;
1197 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001198 *outIsWideColorDisplay = display->hasWideColorGamut();
1199 return NO_ERROR;
1200}
1201
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001203 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001204 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205
Dominik Laskowski6505f792019-09-18 11:10:05 -07001206 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1207 mEventQueue->setEventConnection(
1208 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001209 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001210 }));
1211
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212 return NO_ERROR;
1213}
1214
1215status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001216 Mutex::Autolock lock(mStateLock);
1217 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218}
1219
Lloyd Pique755e3192018-01-31 16:46:15 -08001220status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1221 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001222 // Try to acquire a lock for 1s, fail gracefully
1223 const status_t err = mStateLock.timedLock(s2ns(1));
1224 const bool locked = (err == NO_ERROR);
1225 if (!locked) {
1226 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1227 return TIMED_OUT;
1228 }
1229
1230 outLayers->clear();
1231 mCurrentState.traverseInZOrder([&](Layer* layer) {
1232 outLayers->push_back(layer->getLayerDebugInfo());
1233 });
1234
1235 mStateLock.unlock();
1236 return NO_ERROR;
1237}
1238
Peiyong Linc6780972018-10-28 15:24:08 -07001239status_t SurfaceFlinger::getCompositionPreference(
1240 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1241 Dataspace* outWideColorGamutDataspace,
1242 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001243 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001244 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001245 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001246 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001247 return NO_ERROR;
1248}
1249
Dan Stozaec460082018-12-17 15:35:09 -08001250status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1251 const sp<IBinder>& stopLayerHandle,
1252 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001253 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001254 return BAD_VALUE;
1255 }
1256 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001257 return NO_ERROR;
1258}
1259
Dan Stozaec460082018-12-17 15:35:09 -08001260status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001261 if (!listener) {
1262 return BAD_VALUE;
1263 }
Dan Stozaec460082018-12-17 15:35:09 -08001264 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001265 return NO_ERROR;
1266}
Dan Gittik57e63c52019-01-18 16:37:54 +00001267
1268status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1269 bool* outSupport) const {
1270 if (!displayToken || !outSupport) {
1271 return BAD_VALUE;
1272 }
1273 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1274 if (!displayId) {
1275 return NAME_NOT_FOUND;
1276 }
1277 *outSupport =
1278 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1279 return NO_ERROR;
1280}
1281
1282status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1283 float brightness) const {
1284 if (!displayToken) {
1285 return BAD_VALUE;
1286 }
1287 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1288 if (!displayId) {
1289 return NAME_NOT_FOUND;
1290 }
1291 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1292}
1293
Ady Abraham8532d012019-05-08 14:50:56 -07001294status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1295 PowerHint powerHint = static_cast<PowerHint>(hintId);
1296
1297 if (powerHint == PowerHint::INTERACTION) {
1298 mScheduler->notifyTouchEvent();
1299 }
1300
1301 return NO_ERROR;
1302}
1303
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001304// ----------------------------------------------------------------------------
1305
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001306sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001307 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001308 const auto& handle =
1309 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001310
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001311 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001312}
1313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001314// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001315
1316void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001317 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001318}
1319
1320void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001321 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001322 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001323}
1324
1325void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001326 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001327 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001328}
1329
1330void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001331 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001332 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001333}
1334
1335status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001336 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001337 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338}
1339
1340status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001341 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001342 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001343 if (res == NO_ERROR) {
1344 msg->wait();
1345 }
1346 return res;
1347}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001348
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001349void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001350 do {
1351 waitForEvent();
1352 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001353}
1354
Dominik Laskowski83b88212018-12-11 13:34:06 -08001355nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001356 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001357 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1358 return 0;
1359 }
1360
1361 const auto config = getHwComposer().getActiveConfig(*displayId);
1362 return config ? config->getVsyncPeriod() : 0;
1363}
1364
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001365void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001366 int64_t timestamp,
1367 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001368 ATRACE_NAME("SF onVsync");
1369
Ady Abraham7159f572019-10-11 11:10:18 -07001370 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1371
Steven Thomas3cfac282017-02-06 12:29:30 -08001372 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001374 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001375 return;
1376 }
1377
Dominik Laskowski075d3172018-05-24 15:50:06 -07001378 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001379 return;
1380 }
1381
Dominik Laskowski075d3172018-05-24 15:50:06 -07001382 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001383 // For now, we don't do anything with external display vsyncs.
1384 return;
1385 }
1386
Alec Mourif8e689c2019-05-20 18:32:22 -07001387 bool periodFlushed = false;
1388 mScheduler->addResyncSample(timestamp, &periodFlushed);
1389 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001390 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001391 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001392}
1393
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001394void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001395 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1396 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397}
1398
Ady Abraham261614e2019-07-10 17:53:12 -07001399bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001400 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001401}
1402
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001403void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001404 const auto display = getDefaultDisplayDeviceLocked();
1405 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001406 return;
1407 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001408 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001409
Ana Krulec7d1d6832018-12-27 11:10:09 -08001410 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001411 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1412 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001413
Dominik Laskowski22488f62019-03-28 09:53:04 -07001414 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001415 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1416 return;
1417 }
1418
Dominik Laskowski22488f62019-03-28 09:53:04 -07001419 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001420}
1421
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001422void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001423 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001424 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001425 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001426
Lloyd Piqueba04e622017-12-14 17:11:26 -08001427 // Ignore events that do not have the right sequenceId.
1428 if (sequenceId != getBE().mComposerSequenceId) {
1429 return;
1430 }
1431
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 // Only lock if we're not on the main thread. This function is normally
1433 // called on a hwbinder thread, but for the primary display it's called on
1434 // the main thread with the state lock already held, so don't attempt to
1435 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001436 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001437
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001438 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001439
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001440 if (std::this_thread::get_id() == mMainThreadId) {
1441 // Process all pending hot plug events immediately if we are on the main thread.
1442 processDisplayHotplugEventsLocked();
1443 }
1444
Lloyd Piqueba04e622017-12-14 17:11:26 -08001445 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001446}
1447
Ady Abraham7159f572019-10-11 11:10:18 -07001448void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
1449 int32_t /*sequenceId*/, hwc2_display_t /*display*/,
1450 const hwc_vsync_period_change_timeline_t& /*updatedTimeline*/) {
1451 // TODO(b/142753004): use timeline when changing refresh rate
1452}
1453
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001454void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001455 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001456 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001458 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001459 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001460}
1461
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001462void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001463 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001464
1465 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1466 // display power state.
1467 postMessageAsync(new LambdaMessage(
1468 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1469}
1470
1471void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1472 ATRACE_CALL();
1473
Ady Abraham27c70212019-06-11 10:52:26 -07001474 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001476 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001477 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1478 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001479 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001480 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001481 }
Mathias Agopian86303202012-07-24 22:46:10 -07001482}
1483
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001484// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001485void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001486 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001487 // Clear the drawing state so that the logic inside of
1488 // handleTransactionLocked will fire. It will determine the delta between
1489 // mCurrentState and mDrawingState and re-apply all changes when we make the
1490 // transition.
1491 mDrawingState.displays.clear();
1492 mDisplays.clear();
1493}
1494
Steven Thomas050b2c82017-03-06 11:45:16 -08001495void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001496 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001497 if (!mVrFlinger)
1498 return;
1499 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001500 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001501 return;
1502 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001503
Lloyd Pique441d5042018-10-18 16:49:51 -07001504 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001505 ALOGE("Vr flinger is only supported for remote hardware composer"
1506 " service connections. Ignoring request to transition to vr"
1507 " flinger.");
1508 mVrFlingerRequestsDisplay = false;
1509 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001510 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001511
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001512 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001513
Steven Thomas0123ac62018-07-12 11:32:34 -07001514 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001515 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001516
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001517 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001518
1519 // Clear out all the output layers from the composition engine for all
1520 // displays before destroying the hardware composer interface. This ensures
1521 // any HWC layers are destroyed through that interface before it becomes
1522 // invalid.
1523 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001524 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001525 }
1526
Steven Thomas0123ac62018-07-12 11:32:34 -07001527 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1528 // called below. Clear the reference now so we don't accidentally use it
1529 // later.
1530 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001533 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001534 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001535
Steven Thomasb02664d2017-07-26 18:48:28 -07001536 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001537 // Delete the current instance before creating the new one
1538 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1539 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1540 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1541 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542
Lloyd Pique441d5042018-10-18 16:49:51 -07001543 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001544 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001545
1546 if (vrFlingerRequestsDisplay) {
1547 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001548 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001549
1550 mVisibleRegionsDirty = true;
1551 invalidateHwcGeometry();
1552
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001553 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001554 display = getDefaultDisplayDeviceLocked();
1555 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001556 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001557
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001559 const nsecs_t vsyncPeriod = getVsyncPeriod();
1560 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001561
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001562 // The present fences returned from vr_hwc are not an accurate
1563 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001564 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001565
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 // Use phase of 0 since phase is not known.
1567 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001568 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001569 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001570
Ana Krulecc2870422019-01-29 19:00:58 -08001571 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001572
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001573 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001574 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001575}
1576
Ady Abraham11579302019-09-19 12:35:58 -07001577bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1578 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001579 // We are storing the last 2 present fences. If sf's phase offset is to be
1580 // woken up before the actual vsync but targeting the next vsync, we need to check
1581 // fence N-2
1582 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001583 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001584 ? mPreviousPresentFences[0]
1585 : mPreviousPresentFences[1];
1586
Ady Abraham11579302019-09-19 12:35:58 -07001587 if (fence == Fence::NO_FENCE) {
1588 return false;
1589 }
1590
1591 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1592 fence->wait(graceTimeMs);
1593 }
1594
1595 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001596}
1597
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001598void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001599 DisplayStatInfo stats;
1600 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001601 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001602 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001603 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001604 mPhaseOffsets->getOffsetThresholdForNextVsync()
1605 ? presentTime
1606 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001607}
1608
Dominik Laskowski22488f62019-03-28 09:53:04 -07001609void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001610 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001611 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001612 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001613 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001614 // calculate the expected present time once and use the cached
1615 // value throughout this frame to make sure all layers are
1616 // seeing this same value.
1617 populateExpectedPresentTime();
1618
Ady Abraham11579302019-09-19 12:35:58 -07001619 // When Backpressure propagation is enabled we want to give a small grace period
1620 // for the present fence to fire instead of just giving up on this frame to handle cases
1621 // where present fence is just about to get signaled.
1622 const int graceTimeForPresentFenceMs =
1623 (mPropagateBackpressure &&
1624 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1625 ? 1
1626 : 0;
1627 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1628 previousFrameMissed(
1629 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001630 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1631 mHadDeviceComposition && frameMissed};
1632 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1633 mHadClientComposition && frameMissed};
1634
Alec Mouricc0fc602019-02-26 21:45:19 -08001635 if (frameMissed) {
1636 mFrameMissedCount++;
1637 mTimeStats->incrementMissedFrames();
1638 }
1639
Alec Mouri40189b02019-03-05 15:07:54 -08001640 if (hwcFrameMissed) {
1641 mHwcFrameMissedCount++;
1642 }
1643
1644 if (gpuFrameMissed) {
1645 mGpuFrameMissedCount++;
1646 }
1647
Dominik Laskowski49cea512019-11-12 14:13:23 -08001648 mScheduler->chooseRefreshRateForContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001649
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
Alec Mouri9519bf12019-11-15 16:54:44 -08001678 if (mFrameStartTime <= 0) {
1679 // We should only use the time of the first invalidate
1680 // message that signals a refresh as the beginning of the
1681 // frame. Otherwise the real frame time will be
1682 // underestimated.
1683 mFrameStartTime = frameStart;
1684 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001685 signalRefresh();
1686 }
1687 break;
1688 }
1689 case MessageQueue::REFRESH: {
1690 handleMessageRefresh();
1691 break;
1692 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001693 }
1694}
1695
Dan Stoza6b9454d2014-11-07 16:00:59 -08001696bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001697 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001698 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001699
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001700 bool flushedATransaction = flushTransactionQueues();
1701
1702 bool runHandleTransaction = transactionFlags &&
1703 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1704
1705 if (runHandleTransaction) {
1706 handleTransaction(eTransactionMask);
1707 } else {
1708 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001709 }
1710
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001711 if (transactionFlushNeeded()) {
1712 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001713 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001714
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001715 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001716}
1717
Mathias Agopian4fec8732012-06-29 14:12:52 -07001718void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001719 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001720
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001721 mRefreshPending = false;
1722
Lloyd Piqueab039b52019-02-13 14:22:42 -08001723 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001724 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001725 for (const auto& [_, display] : mDisplays) {
1726 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1727 }
1728 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1729 auto compositionLayer = layer->getCompositionLayer();
1730 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1731 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001732 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1733 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1734 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001735 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001736 }
1737
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001738 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001739 refreshArgs.outputColorSetting = useColorManagement
1740 ? mDisplayColorSetting
1741 : compositionengine::OutputColorSetting::kUnmanaged;
1742 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1743 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001744
1745 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1746 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001747
1748 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1749 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1750 mDrawingState.colorMatrixChanged = false;
1751 }
1752
1753 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1754
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001755 if (mDebugRegion != 0) {
1756 refreshArgs.devOptFlashDirtyRegionsDelay =
1757 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1758 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001759
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001760 mGeometryInvalid = false;
1761
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001762 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001763 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1764 // Reset the frame start time now that we've recorded this frame.
1765 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001766
David Sodmanfa9b2af2017-12-24 13:28:59 -08001767 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001768 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001769
Lloyd Pique66d68602019-02-13 14:23:31 -08001770 mHadClientComposition =
1771 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1772 auto& displayDevice = tokenDisplayPair.second;
1773 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1774 });
1775 mHadDeviceComposition =
1776 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1777 auto& displayDevice = tokenDisplayPair.second;
1778 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1779 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001780
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001781 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001782
David Sodman7e4ae112018-02-09 15:02:28 -08001783 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001784 if (mVisibleRegionsDirty) {
1785 mVisibleRegionsDirty = false;
1786 if (mTracingEnabled) {
1787 mTracing.notify("visibleRegionsDirty");
1788 }
1789 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001790
1791 if (mCompositionEngine->needsAnotherUpdate()) {
1792 signalLayerUpdate();
1793 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001794}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001795
David Sodmanfa9b2af2017-12-24 13:28:59 -08001796
1797bool SurfaceFlinger::handleMessageInvalidate() {
1798 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001799 bool refreshNeeded = handlePageFlip();
1800
Vishnu Nair4351ad52019-02-11 14:13:02 -08001801 if (mVisibleRegionsDirty) {
1802 computeLayerBounds();
1803 }
1804
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001805 for (auto& layer : mLayersPendingRefresh) {
1806 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001807 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001808 invalidateLayerStack(layer, visibleReg);
1809 }
1810 mLayersPendingRefresh.clear();
1811 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001812}
1813
Ana Krulece588e312018-09-18 12:32:24 -07001814void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1815 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001816 // Update queue of past composite+present times and determine the
1817 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001818 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001819 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001820 while (!getBE().mCompositePresentTimes.empty()) {
1821 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001822 // Cached values should have been updated before calling this method,
1823 // which helps avoid duplicate syscalls.
1824 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1825 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1826 break;
1827 }
1828 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001829 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001830 }
1831
1832 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001833 while (getBE().mCompositePresentTimes.size() > 16) {
1834 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001835 }
1836
Ana Krulece588e312018-09-18 12:32:24 -07001837 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001838}
1839
Ana Krulece588e312018-09-18 12:32:24 -07001840void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1841 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001842 // Integer division and modulo round toward 0 not -inf, so we need to
1843 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001844 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1845 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1846 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001847
Ana Krulec757f63a2019-01-25 10:46:18 -08001848 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001849 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001850 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001851 }
1852
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853 // Snap the latency to a value that removes scheduling jitter from the
1854 // composition and present times, which often have >1ms of jitter.
1855 // Reducing jitter is important if an app attempts to extrapolate
1856 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001857 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001858 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001859 nsecs_t bias = stats.vsyncPeriod / 2;
1860 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1861 nsecs_t snappedCompositeToPresentLatency =
1862 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001863
David Sodman99974d22017-11-28 12:04:33 -08001864 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001865 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1866 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001867 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001868}
1869
David Sodman2b406362017-12-15 13:33:47 -08001870void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001871{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001872 ATRACE_CALL();
1873 ALOGV("postComposition");
1874
Brian Anderson3546a3f2016-07-14 11:51:14 -07001875 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001876 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001877 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001878 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001879 }
1880
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001881 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001882 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001883
David Sodman73beded2017-11-15 11:56:06 -08001884 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001885 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001886 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001887 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001888 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1889 ->getRenderSurface()
1890 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001891 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892 } else {
1893 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1894 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001895
David Sodman73beded2017-11-15 11:56:06 -08001896 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001897 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1898 mPreviousPresentFences[0] = displayDevice
1899 ? getHwComposer().getPresentFence(*displayDevice->getId())
1900 : Fence::NO_FENCE;
1901 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001902 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001903
Ana Krulece588e312018-09-18 12:32:24 -07001904 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001905 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001906
Lloyd Piqueab039b52019-02-13 14:22:42 -08001907 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1908 // be sampled a little later than when we started doing work for this frame,
1909 // but that should be okay since updateCompositorTiming has snapping logic.
1910 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1911 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001912 CompositorTiming compositorTiming;
1913 {
David Sodman99974d22017-11-28 12:04:33 -08001914 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1915 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001916 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001917
Robert Carr2047fae2016-11-28 14:09:09 -08001918 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08001919 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
1920 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001921 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001922 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001923 }
Robert Carr2047fae2016-11-28 14:09:09 -08001924 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001925
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001926 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001927 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001928 }
1929
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001930 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001931 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1932 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001933 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001934 }
1935 }
1936
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001937 if (mAnimCompositionPending) {
1938 mAnimCompositionPending = false;
1939
Brian Anderson4e606e32017-03-16 15:34:57 -07001940 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001941 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001942 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001943 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001944 // The HWC doesn't support present fences, so use the refresh
1945 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001946 const nsecs_t presentTime =
1947 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001948 mAnimFrameTracker.setActualPresentTime(presentTime);
1949 }
1950 mAnimFrameTracker.advanceFrame();
1951 }
Dan Stozab90cf072015-03-05 11:05:59 -08001952
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001953 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001954 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001955 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001956 }
1957
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001958 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001959
Lloyd Pique32cbe282018-10-19 13:09:22 -07001960 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1961 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001962 return;
1963 }
1964
1965 nsecs_t currentTime = systemTime();
1966 if (mHasPoweredOff) {
1967 mHasPoweredOff = false;
1968 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001969 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001970 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001971 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1972 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001973 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001974 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001975 }
David Sodman4a36e932017-11-07 14:29:47 -08001976 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001977 }
David Sodman4a36e932017-11-07 14:29:47 -08001978 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001979
1980 {
1981 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001982 if (mTexturePool.size() < mTexturePoolSize) {
1983 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001984 const size_t offset = mTexturePool.size();
1985 mTexturePool.resize(mTexturePoolSize);
1986 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1987 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001988 } else if (mTexturePool.size() > mTexturePoolSize) {
1989 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1990 const size_t offset = mTexturePoolSize;
1991 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1992 mTexturePool.resize(mTexturePoolSize);
1993 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001994 }
1995 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001996
Ady Abrahambe0f9482019-04-24 15:41:53 -07001997 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001998 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001999
Kevin DuBois413287f2019-02-25 08:46:47 -08002000 if (mLumaSampling && mRegionSamplingThread) {
2001 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002002 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002003
2004 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2005 // side-effect of getTotalSize(), so we check that again here
2006 if (ATRACE_ENABLED()) {
2007 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2008 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009}
2010
Vishnu Nair4351ad52019-02-11 14:13:02 -08002011void SurfaceFlinger::computeLayerBounds() {
2012 for (const auto& pair : mDisplays) {
2013 const auto& displayDevice = pair.second;
2014 const auto display = displayDevice->getCompositionDisplay();
2015 for (const auto& layer : mDrawingState.layersSortedByZ) {
2016 // only consider the layers on the given layer stack
2017 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002018 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002019 }
2020
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002021 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2022 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002023 }
2024 }
2025}
2026
David Sodmanfa9b2af2017-12-24 13:28:59 -08002027void SurfaceFlinger::postFrame()
2028{
2029 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002030 const auto display = getDefaultDisplayDeviceLocked();
2031 if (display && getHwComposer().isConnected(*display->getId())) {
2032 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002033 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2034 logFrameStats();
2035 }
2036 }
2037}
2038
Mathias Agopian87baae12012-07-31 12:38:26 -07002039void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002040{
Mathias Agopian841cde52012-03-01 15:44:37 -08002041 ATRACE_CALL();
2042
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002043 // here we keep a copy of the drawing state (that is the state that's
2044 // going to be overwritten by handleTransactionLocked()) outside of
2045 // mStateLock so that the side-effects of the State assignment
2046 // don't happen with mStateLock held (which can cause deadlocks).
2047 State drawingState(mDrawingState);
2048
Mathias Agopianca4d3602011-05-19 15:38:14 -07002049 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002050 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002051
Mathias Agopianca4d3602011-05-19 15:38:14 -07002052 // Here we're guaranteed that some transaction flags are set
2053 // so we can call handleTransactionLocked() unconditionally.
2054 // We call getTransactionFlags(), which will also clear the flags,
2055 // with mStateLock held to guarantee that mCurrentState won't change
2056 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002057
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002058 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002059 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002060 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002061
Mathias Agopianca4d3602011-05-19 15:38:14 -07002062 mDebugInTransaction = 0;
2063 invalidateHwcGeometry();
2064 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002065}
2066
Lloyd Piqueba04e622017-12-14 17:11:26 -08002067void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2068 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002069 const std::optional<DisplayIdentificationInfo> info =
2070 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002071
Dominik Laskowski075d3172018-05-24 15:50:06 -07002072 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002073 continue;
2074 }
2075
Lloyd Piqueba04e622017-12-14 17:11:26 -08002076 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002077 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002078 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002079 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2080 initScheduler(info->id);
2081 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002082 mPhysicalDisplayTokens[info->id] = new BBinder();
2083 DisplayDeviceState state;
2084 state.displayId = info->id;
2085 state.isSecure = true; // All physical displays are currently considered secure.
2086 state.displayName = info->name;
2087 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2088 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002089 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002090 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002091 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002092
Dominik Laskowski075d3172018-05-24 15:50:06 -07002093 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2094 if (index >= 0) {
2095 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2096 mInterceptor->saveDisplayDeletion(state.sequenceId);
2097 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002098 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002099 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002100 }
2101
2102 processDisplayChangesLocked();
2103 }
2104
2105 mPendingHotplugEvents.clear();
2106}
2107
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002108void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002109 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2110 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002111}
2112
Lloyd Pique99d3da52018-01-22 17:48:03 -08002113sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002114 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002115 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002116 const sp<IGraphicBufferProducer>& producer) {
2117 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002118 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002119 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002120 creationArgs.isSecure = state.isSecure;
2121 creationArgs.displaySurface = dispSurface;
2122 creationArgs.hasWideColorGamut = false;
2123 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002124 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002125
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002126 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002127 creationArgs.isPrimary = isInternalDisplay;
2128
2129 if (useColorManagement && displayId) {
2130 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002131 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002132 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002133 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002134 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002135
Dominik Laskowski7e045462018-05-30 13:02:02 -07002136 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002137 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002138 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002139 }
tangrobin6753a022018-08-10 10:58:54 +08002140 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002141
Dominik Laskowski075d3172018-05-24 15:50:06 -07002142 if (displayId) {
2143 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002144 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002145 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002146 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002147
Lloyd Pique90c115d2018-09-18 21:39:42 -07002148 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002149 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002150 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002151
Lloyd Pique99d3da52018-01-22 17:48:03 -08002152 // Make sure that composition can never be stalled by a virtual display
2153 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002154 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002155 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002156 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2157 }
2158
Dominik Laskowski075d3172018-05-24 15:50:06 -07002159 creationArgs.displayInstallOrientation =
2160 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002161
Lloyd Pique99d3da52018-01-22 17:48:03 -08002162 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002163 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002164
Lloyd Pique90c115d2018-09-18 21:39:42 -07002165 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002166
2167 if (maxFrameBufferAcquiredBuffers >= 3) {
2168 nativeWindowSurface->preallocateBuffers();
2169 }
2170
2171 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002172 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002173 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002174 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002175 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002176 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002177 display->getCompositionDisplay()->setColorProfile(
2178 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2179 RenderIntent::COLORIMETRIC,
2180 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002181 if (!state.isVirtual()) {
2182 LOG_ALWAYS_FATAL_IF(!displayId);
2183 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002184 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002186 display->setLayerStack(state.layerStack);
2187 display->setProjection(state.orientation, state.viewport, state.frame);
2188 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002189
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002190 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002191}
2192
Lloyd Pique347200f2017-12-14 17:00:15 -08002193void SurfaceFlinger::processDisplayChangesLocked() {
2194 // here we take advantage of Vector's copy-on-write semantics to
2195 // improve performance by skipping the transaction entirely when
2196 // know that the lists are identical
2197 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2198 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2199 if (!curr.isIdenticalTo(draw)) {
2200 mVisibleRegionsDirty = true;
2201 const size_t cc = curr.size();
2202 size_t dc = draw.size();
2203
2204 // find the displays that were removed
2205 // (ie: in drawing state but not in current state)
2206 // also handle displays that changed
2207 // (ie: displays that are in both lists)
2208 for (size_t i = 0; i < dc;) {
2209 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2210 if (j < 0) {
2211 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002213 // Save display ID before disconnecting.
2214 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002215 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002216
2217 if (!display->isVirtual()) {
2218 LOG_ALWAYS_FATAL_IF(!displayId);
2219 dispatchDisplayHotplugEvent(displayId->value, false);
2220 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002221 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002222
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002223 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002224 } else {
2225 // this display is in both lists. see if something changed.
2226 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002227 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002228 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2229 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2230 if (state_binder != draw_binder) {
2231 // changing the surface is like destroying and
2232 // recreating the DisplayDevice, so we just remove it
2233 // from the drawing state, so that it get re-added
2234 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002235 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002236 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002237 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002238 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002239 mDrawingState.displays.removeItemsAt(i);
2240 dc--;
2241 // at this point we must loop to the next item
2242 continue;
2243 }
2244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002246 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002248 }
2249 if ((state.orientation != draw[i].orientation) ||
2250 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002251 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002252 }
2253 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002254 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002255 }
2256 }
2257 }
2258 ++i;
2259 }
2260
2261 // find displays that were added
2262 // (ie: in current state but not in drawing state)
2263 for (size_t i = 0; i < cc; i++) {
2264 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2265 const DisplayDeviceState& state(curr[i]);
2266
Lloyd Pique542307f2018-10-19 13:24:08 -07002267 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002268 sp<IGraphicBufferProducer> producer;
2269 sp<IGraphicBufferProducer> bqProducer;
2270 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002271 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002272
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002274 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002275 // Virtual displays without a surface are dormant:
2276 // they have external state (layer stack, projection,
2277 // etc.) but no internal state (i.e. a DisplayDevice).
2278 if (state.surface != nullptr) {
2279 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002281 int width = 0;
2282 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2283 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2284 int height = 0;
2285 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2286 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2287 int intFormat = 0;
2288 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2289 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002290 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002291
Dominik Laskowski075d3172018-05-24 15:50:06 -07002292 displayId =
2293 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002294 }
2295
2296 // TODO: Plumb requested format back up to consumer
2297
2298 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002299 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002300 bqProducer, bqConsumer,
2301 state.displayName);
2302
2303 dispSurface = vds;
2304 producer = vds;
2305 }
2306 } else {
2307 ALOGE_IF(state.surface != nullptr,
2308 "adding a supported display, but rendering "
2309 "surface is provided (%p), ignoring it",
2310 state.surface.get());
2311
Dominik Laskowski075d3172018-05-24 15:50:06 -07002312 displayId = state.displayId;
2313 LOG_ALWAYS_FATAL_IF(!displayId);
2314 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002315 producer = bqProducer;
2316 }
2317
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002318 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002319 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002320 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002321 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002322 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002323 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002324 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002325 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002326 }
2327 }
2328 }
2329 }
2330 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002331
2332 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002333}
2334
Mathias Agopian87baae12012-07-31 12:38:26 -07002335void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002336{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002337 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2338
Dan Stoza7dde5992015-05-22 09:51:44 -07002339 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002340 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2341 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002342 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002343
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 /*
2345 * Traversal of the children
2346 * (perform the transaction for each of them if needed)
2347 */
2348
Marissa Wall06255332019-03-27 13:48:27 -07002349 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002350 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002351 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002352 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002353
2354 const uint32_t flags = layer->doTransaction(0);
2355 if (flags & Layer::eVisibleRegion)
2356 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002357
2358 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002359 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002360 }
Robert Carr2047fae2016-11-28 14:09:09 -08002361 });
Marissa Wall06255332019-03-27 13:48:27 -07002362 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363 }
2364
2365 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002366 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367 */
2368
Mathias Agopiane57f2922012-08-09 16:29:12 -07002369 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002371 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002372 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002373
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002374 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002375 // The transform hint might have changed for some layers
2376 // (either because a display has changed, or because a layer
2377 // as changed).
2378 //
2379 // Walk through all the layers in currentLayers,
2380 // and update their transform hint.
2381 //
2382 // If a layer is visible only on a single display, then that
2383 // display is used to calculate the hint, otherwise we use the
2384 // default display.
2385 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002386 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002387 // the hint is set before we acquire a buffer from the surface texture.
2388 //
2389 // NOTE: layer transactions have taken place already, so we use their
2390 // drawing state. However, SurfaceFlinger's own transaction has not
2391 // happened yet, so we must use the current state layer list
2392 // (soon to become the drawing state list).
2393 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002394 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002395 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002396 bool first = true;
2397 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002398 // NOTE: we rely on the fact that layers are sorted by
2399 // layerStack first (so we don't have to traverse the list
2400 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002401 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002402 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002403 currentlayerStack = layerStack;
2404 // figure out if this layerstack is mirrored
2405 // (more than one display) if so, pick the default display,
2406 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002407 hintDisplay = nullptr;
2408 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002409 if (display->getCompositionDisplay()
2410 ->belongsInOutput(layer->getLayerStack(),
2411 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002412 if (hintDisplay) {
2413 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002414 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002416 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002417 }
2418 }
2419 }
2420 }
Chet Haase91d25932013-04-11 15:24:55 -07002421
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002422 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002423 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2424 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002425
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002426 // could be null when this layer is using a layerStack
2427 // that is not visible on any display. Also can occur at
2428 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002429 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002430 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002431
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002432 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002433 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002434 if (hintDisplay) {
2435 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002436 }
Robert Carr2047fae2016-11-28 14:09:09 -08002437
2438 first = false;
2439 });
Mathias Agopian84300952012-11-21 16:02:13 -08002440 }
2441
2442
Mathias Agopian3559b072012-08-15 13:46:03 -07002443 /*
2444 * Perform our own transaction if needed
2445 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002446
2447 if (mLayersAdded) {
2448 mLayersAdded = false;
2449 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002450 mVisibleRegionsDirty = true;
2451 }
2452
2453 // some layers might have been removed, so
2454 // we need to update the regions they're exposing.
2455 if (mLayersRemoved) {
2456 mLayersRemoved = false;
2457 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002458 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002459 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002460 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002461 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002462 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002463 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002464 }
Robert Carr2047fae2016-11-28 14:09:09 -08002465 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466 }
2467
Vishnu Nairec0ab382019-02-13 15:32:56 -08002468 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002470}
2471
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002472void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002473 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002474 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002475 return;
2476 }
2477
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002478 if (mVisibleRegionsDirty || mInputInfoChanged) {
2479 mInputInfoChanged = false;
2480 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002481 } else if (mInputWindowCommands.syncInputWindows) {
2482 // If the caller requested to sync input windows, but there are no
2483 // changes to input windows, notify immediately.
2484 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002485 }
2486
Arthur Hung6cbb9752019-09-05 16:38:18 +08002487 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002488}
2489
2490void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002491 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002492
2493 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2494 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002495 // When calculating the screen bounds we ignore the transparent region since it may
2496 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002497 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002498 }
2499 });
chaviw291d88a2019-02-14 10:33:58 -08002500
2501 mInputFlinger->setInputWindows(inputHandles,
2502 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2503 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002504}
2505
Vishnu Nairec0ab382019-02-13 15:32:56 -08002506void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002507 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002508 mPendingInputWindowCommands.clear();
2509}
2510
Riley Andrews03414a12014-07-01 14:22:59 -07002511void SurfaceFlinger::updateCursorAsync()
2512{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002513 compositionengine::CompositionRefreshArgs refreshArgs;
2514 for (const auto& [_, display] : mDisplays) {
2515 if (display->getId()) {
2516 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002517 }
2518 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002519
2520 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002521}
2522
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002523void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2524 if (mScheduler) {
2525 // In practice it's not allowed to hotplug in/out the primary display once it's been
2526 // connected during startup, but some tests do it, so just warn and return.
2527 ALOGW("Can't re-init scheduler");
2528 return;
2529 }
2530
2531 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2532 mRefreshRateConfigs =
2533 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2534 getHwComposer().getConfigs(
2535 primaryDisplayId),
2536 currentConfig);
2537 mRefreshRateStats =
2538 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2539 currentConfig, HWC_POWER_MODE_OFF);
2540 mRefreshRateStats->setConfigMode(currentConfig);
2541
2542 // start the EventThread
2543 mScheduler =
2544 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2545 *mRefreshRateConfigs);
2546 mAppConnectionHandle =
2547 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2548 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2549 impl::EventThread::InterceptVSyncsCallback());
2550 mSfConnectionHandle =
2551 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2552 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2553 [this](nsecs_t timestamp) {
2554 mInterceptor->saveVSyncEvent(timestamp);
2555 });
2556
2557 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2558 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2559 mPhaseOffsets->getCurrentOffsets());
2560
2561 mRegionSamplingThread =
2562 new RegionSamplingThread(*this, *mScheduler,
2563 RegionSamplingThread::EnvironmentTimingTunables());
2564
2565 mScheduler->setChangeRefreshRateCallback(
2566 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2567 Mutex::Autolock lock(mStateLock);
2568 setRefreshRateTo(type, event);
2569 });
2570}
2571
Mathias Agopian4fec8732012-06-29 14:12:52 -07002572void SurfaceFlinger::commitTransaction()
2573{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002574 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002575
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002576 mTransactionPending = false;
2577 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002578 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002579}
2580
Lloyd Pique58e24a32019-08-01 15:50:14 -07002581void SurfaceFlinger::commitTransactionLocked() {
2582 if (!mLayersPendingRemoval.isEmpty()) {
2583 // Notify removed layers now that they can't be drawn from
2584 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002585 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002586
2587 // Ensure any buffers set to display on any children are released.
2588 if (l->isRemovedFromCurrentState()) {
2589 l->latchAndReleaseBuffer();
2590 }
2591
2592 // If the layer has been removed and has no parent, then it will not be reachable
2593 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2594 // ensure we can copy its current to drawing state.
2595 if (!l->getParent()) {
2596 mOffscreenLayers.emplace(l.get());
2597 }
2598 }
2599 mLayersPendingRemoval.clear();
2600 }
2601
2602 // If this transaction is part of a window animation then the next frame
2603 // we composite should be considered an animation as well.
2604 mAnimCompositionPending = mAnimTransactionPending;
2605
2606 mDrawingState = mCurrentState;
2607 // clear the "changed" flags in current state
2608 mCurrentState.colorMatrixChanged = false;
2609
2610 mDrawingState.traverseInZOrder([&](Layer* layer) {
2611 layer->commitChildList();
2612
2613 // If the layer can be reached when traversing mDrawingState, then the layer is no
2614 // longer offscreen. Remove the layer from the offscreenLayer set.
2615 if (mOffscreenLayers.count(layer)) {
2616 mOffscreenLayers.erase(layer);
2617 }
2618 });
2619
2620 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002621 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002622}
2623
Nataniel Borges2b796da2019-02-15 13:32:18 -08002624void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2625 if (mTracingEnabledChanged) {
2626 mTracingEnabled = mTracing.isEnabled();
2627 mTracingEnabledChanged = false;
2628 }
2629
2630 // Synchronize with Tracing thread
2631 std::unique_lock<std::mutex> lock;
2632 if (mTracingEnabled) {
2633 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2634 }
2635
2636 lockedOperation();
2637
2638 // Synchronize with Tracing thread
2639 if (mTracingEnabled) {
2640 lock.unlock();
2641 }
2642}
2643
chaviw74d90ad2019-04-26 14:45:26 -07002644void SurfaceFlinger::commitOffscreenLayers() {
2645 for (Layer* offscreenLayer : mOffscreenLayers) {
2646 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2647 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2648 if (!trFlags) return;
2649
2650 layer->doTransaction(0);
2651 layer->commitChildList();
2652 });
2653 }
2654}
2655
Chia-I Wuab0c3192017-08-01 11:29:00 -07002656void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002657 for (const auto& [token, displayDevice] : mDisplays) {
2658 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002659 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002660 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002661 }
2662 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002663}
2664
Dan Stoza6b9454d2014-11-07 16:00:59 -08002665bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002666{
Ady Abraham09bd3922019-04-08 10:44:56 -07002667 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002668 ALOGV("handlePageFlip");
2669
Brian Andersond6927fb2016-07-23 23:37:30 -07002670 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002671
Mathias Agopian4fec8732012-06-29 14:12:52 -07002672 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002673 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002674 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002675
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002676 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2677
Eric Penner51c59cd2014-07-28 19:51:58 -07002678 // Store the set of layers that need updates. This set must not change as
2679 // buffers are being latched, as this could result in a deadlock.
2680 // Example: Two producers share the same command stream and:
2681 // 1.) Layer 0 is latched
2682 // 2.) Layer 0 gets a new frame
2683 // 2.) Layer 1 gets a new frame
2684 // 3.) Layer 1 is latched.
2685 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2686 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002687 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002688 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002689 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002690 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002691 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002692 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002693 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002694 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002695 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002696 } else {
2697 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002698 }
Robert Carr2047fae2016-11-28 14:09:09 -08002699 });
2700
chaviw49a108c2019-08-12 11:23:06 -07002701 // The client can continue submitting buffers for offscreen layers, but they will not
2702 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2703 // layers to ensure dequeueBuffer doesn't block indefinitely.
2704 for (Layer* offscreenLayer : mOffscreenLayers) {
2705 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2706 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2707 }
2708
Lloyd Piquef2c79392018-12-20 16:23:33 -08002709 if (!mLayersWithQueuedFrames.empty()) {
2710 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2711 // writes to Layer current state. See also b/119481871
2712 Mutex::Autolock lock(mStateLock);
2713
2714 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002715 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002716 mLayersPendingRefresh.push_back(layer);
2717 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002718 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002719 if (layer->isBufferLatched()) {
2720 newDataLatched = true;
2721 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002722 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002723 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002724
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002725 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002726
2727 // If we will need to wake up at some time in the future to deal with a
2728 // queued frame that shouldn't be displayed during this vsync period, wake
2729 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002730 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002731 signalLayerUpdate();
2732 }
2733
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002734 // enter boot animation on first buffer latch
2735 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2736 ALOGI("Enter boot animation");
2737 mBootStage = BootStage::BOOTANIMATION;
2738 }
2739
chaviw74b03172019-08-19 11:09:03 -07002740 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2741
Dan Stoza6b9454d2014-11-07 16:00:59 -08002742 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002743 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744}
2745
Mathias Agopianad456f92011-01-13 17:53:01 -08002746void SurfaceFlinger::invalidateHwcGeometry()
2747{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002748 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002749}
2750
Robert Carrc0df3122019-04-11 13:18:21 -07002751status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2752 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2753 const sp<IBinder>& parentHandle,
2754 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002755 // add this layer to the current state list
2756 {
2757 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002758 sp<Layer> parent;
2759 if (parentHandle != nullptr) {
2760 parent = fromHandle(parentHandle);
2761 if (parent == nullptr) {
2762 return NAME_NOT_FOUND;
2763 }
2764 } else {
2765 parent = parentLayer;
2766 }
2767
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002769 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002770 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002771 return NO_MEMORY;
2772 }
Robert Carrc0df3122019-04-11 13:18:21 -07002773
2774 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2775
Robert Carrb89ea9d2018-12-10 13:01:14 -08002776 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002778 } else if (parent == nullptr) {
2779 lbc->onRemovedFromCurrentState();
2780 } else if (parent->isRemovedFromCurrentState()) {
2781 parent->addChild(lbc);
2782 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002783 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002784 parent->addChild(lbc);
2785 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002786
Yiwei Zhang243b3782018-05-15 17:40:04 -07002787 if (gbc != nullptr) {
2788 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2789 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2790 mMaxGraphicBufferProducerListSize,
2791 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2792 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002793 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002794 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002795 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002796 }
2797
Mathias Agopian96f08192010-06-02 23:28:45 -07002798 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002799 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002800
Dan Stoza7d89d062015-04-30 13:29:25 -07002801 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002802}
2803
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002804uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002805 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002806}
2807
Mathias Agopian3f844832013-08-07 21:24:32 -07002808uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002809 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002810}
2811
Mathias Agopian3f844832013-08-07 21:24:32 -07002812uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002813 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002814}
2815
2816uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002817 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002818 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002819 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002820 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002821 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002822 }
2823 return old;
2824}
2825
Marissa Wall713b63f2018-10-17 15:42:43 -07002826bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002827 // to prevent onHandleDestroyed from being called while the lock is held,
2828 // we must keep a copy of the transactions (specifically the composer
2829 // states) around outside the scope of the lock
2830 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002831 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002832 {
2833 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002834
Valerie Haufce31b82019-04-30 16:41:14 -07002835 auto it = mTransactionQueues.begin();
2836 while (it != mTransactionQueues.end()) {
2837 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002838
Valerie Haufce31b82019-04-30 16:41:14 -07002839 while (!transactionQueue.empty()) {
2840 const auto& transaction = transactionQueue.front();
2841 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002842 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002843 transaction.states)) {
2844 setTransactionFlags(eTransactionFlushNeeded);
2845 break;
2846 }
2847 transactions.push_back(transaction);
2848 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2849 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002850 transaction.buffer, transaction.postTime,
2851 transaction.privileged, transaction.hasListenerCallbacks,
2852 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002853 transactionQueue.pop();
2854 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002855 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002856
Valerie Haufce31b82019-04-30 16:41:14 -07002857 if (transactionQueue.empty()) {
2858 it = mTransactionQueues.erase(it);
2859 mTransactionCV.broadcast();
2860 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002861 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002862 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002863 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002864 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002865 return flushedATransaction;
2866}
2867
2868bool SurfaceFlinger::transactionFlushNeeded() {
2869 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002870}
2871
chaviwca27f252018-02-06 16:46:39 -08002872
Marissa Wall17b4e452018-12-26 16:32:34 -08002873bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002874 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002875 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002876 if (!useCachedExpectedPresentTime)
2877 populateExpectedPresentTime();
2878
2879 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002880 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2881 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2882 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2883 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2884 return false;
2885 }
2886
Marissa Wall713b63f2018-10-17 15:42:43 -07002887 for (const ComposerState& state : states) {
2888 const layer_state_t& s = state.state;
2889 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2890 continue;
2891 }
2892 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002893 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002894 }
2895 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002896 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002897}
2898
Valerie Hau9dab9732019-08-20 09:29:25 -07002899void SurfaceFlinger::setTransactionState(
2900 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2901 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2902 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2903 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002904 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002905
Valerie Haubc6ddb12019-03-08 11:10:15 -08002906 const int64_t postTime = systemTime();
2907
Robert Carr14167e02019-02-13 13:50:55 -08002908 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2909
Mathias Agopian698c0872011-06-28 19:09:31 -07002910 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002911
Marissa Wall713b63f2018-10-17 15:42:43 -07002912 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002913 auto itr = mTransactionQueues.find(applyToken);
2914 // if this is an animation frame, wait until prior animation frame has
2915 // been applied by SF
2916 if (flags & eAnimation) {
2917 while (itr != mTransactionQueues.end()) {
2918 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2919 if (CC_UNLIKELY(err != NO_ERROR)) {
2920 ALOGW_IF(err == TIMED_OUT,
2921 "setTransactionState timed out "
2922 "waiting for animation frame to apply");
2923 break;
2924 }
2925 itr = mTransactionQueues.find(applyToken);
2926 }
2927 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002928
2929 // Expected present time is computed and cached on invalidate, so it may be stale.
2930 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2931 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002932 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002933 uncacheBuffer, postTime, privileged,
2934 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002935 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002936 return;
2937 }
2938
Valerie Haubc6ddb12019-03-08 11:10:15 -08002939 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002940 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2941 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002942}
2943
Valerie Hau9dab9732019-08-20 09:29:25 -07002944void SurfaceFlinger::applyTransactionState(
2945 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2946 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2947 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2948 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2949 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002950 uint32_t transactionFlags = 0;
2951
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002952 if (flags & eAnimation) {
2953 // For window updates that are part of an animation we must wait for
2954 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002955 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002956 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002957 if (CC_UNLIKELY(err != NO_ERROR)) {
2958 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002959 // caller after a few seconds.
2960 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2961 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002962 mAnimTransactionPending = false;
2963 break;
2964 }
2965 }
2966 }
2967
chaviwca27f252018-02-06 16:46:39 -08002968 for (const DisplayState& display : displays) {
2969 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002970 }
2971
Valerie Hau9dab9732019-08-20 09:29:25 -07002972 // start and end registration for listeners w/ no surface so they can get their callback. Note
2973 // that listeners with SurfaceControls will start registration during setClientStateLocked
2974 // below.
2975 for (const auto& listener : listenerCallbacks) {
2976 mTransactionCompletedThread.startRegistration(listener);
2977 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002978 }
2979
Valerie Hau9dab9732019-08-20 09:29:25 -07002980 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002981 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002982 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002983 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2984 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002985 }
2986
Valerie Hau9dab9732019-08-20 09:29:25 -07002987 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002988 mTransactionCompletedThread.endRegistration(listenerCallback);
2989 }
2990
Marissa Walle2ffb422018-10-12 11:33:52 -07002991 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002992 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002993 mTransactionCompletedThread.sendCallbacks();
2994 }
2995 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002996
chaviw273171b2018-12-26 11:46:30 -08002997 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2998
Marissa Wall947d34e2019-03-29 14:03:53 -07002999 if (uncacheBuffer.isValid()) {
3000 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003001 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003002 }
3003
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003004 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3005 // anyway. This can be used as a flush mechanism for previous async transactions.
3006 // Empty animation transaction can be used to simulate back-pressure, so also force a
3007 // transaction for empty animation transactions.
3008 if (transactionFlags == 0 &&
3009 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003010 transactionFlags = eTransactionNeeded;
3011 }
3012
Marissa Wall06255332019-03-27 13:48:27 -07003013 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3014 // so we don't have to wake up again next frame to preform an uneeded traversal.
3015 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3016 transactionFlags = transactionFlags & (~eTraversalNeeded);
3017 mTraversalNeededMainThread = true;
3018 }
3019
Mathias Agopian386aa982011-11-07 21:58:03 -08003020 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003021 if (mInterceptor->isEnabled()) {
3022 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003023 }
Irvel468051e2016-06-13 16:44:44 -07003024
Mathias Agopian386aa982011-11-07 21:58:03 -08003025 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003026 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3027 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003028 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003029
3030 // if this is a synchronous transaction, wait for it to take effect
3031 // before returning.
3032 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003033 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003034 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003035 if (flags & eAnimation) {
3036 mAnimTransactionPending = true;
3037 }
chaviw4fe36852019-04-15 16:25:49 -07003038 if (mPendingInputWindowCommands.syncInputWindows) {
3039 mPendingSyncInputWindows = true;
3040 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003041
3042 // applyTransactionState can be called by either the main SF thread or by
3043 // another process through setTransactionState. While a given process may wish
3044 // to wait on synchronous transactions, the main SF thread should never
3045 // be blocked. Therefore, we only wait if isMainThread is false.
3046 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003047 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3048 if (CC_UNLIKELY(err != NO_ERROR)) {
3049 // just in case something goes wrong in SF, return to the
3050 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003051 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3052 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003053 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003054 break;
3055 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003056 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003057 }
3058}
3059
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003060uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3061 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3062 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003063
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003065 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3066
3067 const uint32_t what = s.what;
3068 if (what & DisplayState::eSurfaceChanged) {
3069 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3070 state.surface = s.surface;
3071 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003072 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003073 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003074 if (what & DisplayState::eLayerStackChanged) {
3075 if (state.layerStack != s.layerStack) {
3076 state.layerStack = s.layerStack;
3077 flags |= eDisplayTransactionNeeded;
3078 }
3079 }
3080 if (what & DisplayState::eDisplayProjectionChanged) {
3081 if (state.orientation != s.orientation) {
3082 state.orientation = s.orientation;
3083 flags |= eDisplayTransactionNeeded;
3084 }
3085 if (state.frame != s.frame) {
3086 state.frame = s.frame;
3087 flags |= eDisplayTransactionNeeded;
3088 }
3089 if (state.viewport != s.viewport) {
3090 state.viewport = s.viewport;
3091 flags |= eDisplayTransactionNeeded;
3092 }
3093 }
3094 if (what & DisplayState::eDisplaySizeChanged) {
3095 if (state.width != s.width) {
3096 state.width = s.width;
3097 flags |= eDisplayTransactionNeeded;
3098 }
3099 if (state.height != s.height) {
3100 state.height = s.height;
3101 flags |= eDisplayTransactionNeeded;
3102 }
3103 }
3104
Mathias Agopiane57f2922012-08-09 16:29:12 -07003105 return flags;
3106}
3107
Robert Carr14167e02019-02-13 13:50:55 -08003108bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003109 IPCThreadState* ipc = IPCThreadState::self();
3110 const int pid = ipc->getCallingPid();
3111 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003112 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003113 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003114 return false;
3115 }
3116 return true;
3117}
3118
Marissa Wall3dad52d2019-03-22 14:03:19 -07003119uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003120 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3121 bool privileged,
3122 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003123 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003124
Valerie Hau9dab9732019-08-20 09:29:25 -07003125 for (auto& listener : s.listeners) {
3126 // note that startRegistration will not re-register if the listener has
3127 // already be registered for a prior surface control
3128 mTransactionCompletedThread.startRegistration(listener);
3129 listenerCallbacks.insert(listener);
3130 }
3131
Vishnu Nairf03652d2019-07-16 17:56:56 -07003132 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003133 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003134 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003135 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003136 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003137 }
chaviw8b3871a2017-11-01 17:41:01 -07003138 return 0;
3139 }
3140
chaviw8b3871a2017-11-01 17:41:01 -07003141 uint32_t flags = 0;
3142
Garfield Tan8a3083e2018-12-03 13:21:07 -08003143 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003144
3145 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3146 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003147 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003148 layer->pushPendingState();
3149 }
3150
chaviw8b3871a2017-11-01 17:41:01 -07003151 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003152 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003153 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003154 }
chaviw8b3871a2017-11-01 17:41:01 -07003155 }
3156 if (what & layer_state_t::eLayerChanged) {
3157 // NOTE: index needs to be calculated before we update the state
3158 const auto& p = layer->getParent();
3159 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003160 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003161 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003162 mCurrentState.layersSortedByZ.removeAt(idx);
3163 mCurrentState.layersSortedByZ.add(layer);
3164 // we need traversal (state changed)
3165 // AND transaction (list changed)
3166 flags |= eTransactionNeeded|eTraversalNeeded;
3167 }
chaviw8b3871a2017-11-01 17:41:01 -07003168 } else {
3169 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003170 flags |= eTransactionNeeded|eTraversalNeeded;
3171 }
3172 }
chaviw8b3871a2017-11-01 17:41:01 -07003173 }
3174 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003175 // NOTE: index needs to be calculated before we update the state
3176 const auto& p = layer->getParent();
3177 if (p == nullptr) {
3178 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3179 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3180 mCurrentState.layersSortedByZ.removeAt(idx);
3181 mCurrentState.layersSortedByZ.add(layer);
3182 // we need traversal (state changed)
3183 // AND transaction (list changed)
3184 flags |= eTransactionNeeded|eTraversalNeeded;
3185 }
3186 } else {
3187 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3188 flags |= eTransactionNeeded|eTraversalNeeded;
3189 }
chaviw8b3871a2017-11-01 17:41:01 -07003190 }
3191 }
3192 if (what & layer_state_t::eSizeChanged) {
3193 if (layer->setSize(s.w, s.h)) {
3194 flags |= eTraversalNeeded;
3195 }
3196 }
3197 if (what & layer_state_t::eAlphaChanged) {
3198 if (layer->setAlpha(s.alpha))
3199 flags |= eTraversalNeeded;
3200 }
3201 if (what & layer_state_t::eColorChanged) {
3202 if (layer->setColor(s.color))
3203 flags |= eTraversalNeeded;
3204 }
Peiyong Lind3788632018-09-18 16:01:31 -07003205 if (what & layer_state_t::eColorTransformChanged) {
3206 if (layer->setColorTransform(s.colorTransform)) {
3207 flags |= eTraversalNeeded;
3208 }
3209 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003210 if (what & layer_state_t::eBackgroundColorChanged) {
3211 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3212 flags |= eTraversalNeeded;
3213 }
3214 }
chaviw8b3871a2017-11-01 17:41:01 -07003215 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003216 // TODO: b/109894387
3217 //
3218 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3219 // rotation. To see the problem observe that if we have a square parent, and a child
3220 // of the same size, then we rotate the child 45 degrees around it's center, the child
3221 // must now be cropped to a non rectangular 8 sided region.
3222 //
3223 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3224 // private API, and the WindowManager only uses rotation in one case, which is on a top
3225 // level layer in which cropping is not an issue.
3226 //
3227 // However given that abuse of rotation matrices could lead to surfaces extending outside
3228 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3229 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3230 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003231 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003232 flags |= eTraversalNeeded;
3233 }
3234 if (what & layer_state_t::eTransparentRegionChanged) {
3235 if (layer->setTransparentRegionHint(s.transparentRegion))
3236 flags |= eTraversalNeeded;
3237 }
3238 if (what & layer_state_t::eFlagsChanged) {
3239 if (layer->setFlags(s.flags, s.mask))
3240 flags |= eTraversalNeeded;
3241 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003242 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003243 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003244 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003245 if (what & layer_state_t::eCornerRadiusChanged) {
3246 if (layer->setCornerRadius(s.cornerRadius))
3247 flags |= eTraversalNeeded;
3248 }
chaviw8b3871a2017-11-01 17:41:01 -07003249 if (what & layer_state_t::eLayerStackChanged) {
3250 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3251 // We only allow setting layer stacks for top level layers,
3252 // everything else inherits layer stack from its parent.
3253 if (layer->hasParent()) {
3254 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003255 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003256 } else if (idx < 0) {
3257 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003258 "that also does not appear in the top level layer list. Something"
3259 " has gone wrong.",
3260 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003261 } else if (layer->setLayerStack(s.layerStack)) {
3262 mCurrentState.layersSortedByZ.removeAt(idx);
3263 mCurrentState.layersSortedByZ.add(layer);
3264 // we need traversal (state changed)
3265 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003266 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003267 }
3268 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003269 if (what & layer_state_t::eDeferTransaction_legacy) {
3270 if (s.barrierHandle_legacy != nullptr) {
3271 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3272 } else if (s.barrierGbp_legacy != nullptr) {
3273 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003274 if (authenticateSurfaceTextureLocked(gbp)) {
3275 const auto& otherLayer =
3276 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003277 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003278 } else {
3279 ALOGE("Attempt to defer transaction to to an"
3280 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003281 }
3282 }
chaviw8b3871a2017-11-01 17:41:01 -07003283 // We don't trigger a traversal here because if no other state is
3284 // changed, we don't want this to cause any more work
3285 }
chaviw8b3871a2017-11-01 17:41:01 -07003286 if (what & layer_state_t::eReparentChildren) {
3287 if (layer->reparentChildren(s.reparentHandle)) {
3288 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003289 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003290 }
chaviw8b3871a2017-11-01 17:41:01 -07003291 if (what & layer_state_t::eDetachChildren) {
3292 layer->detachChildren();
3293 }
3294 if (what & layer_state_t::eOverrideScalingModeChanged) {
3295 layer->setOverrideScalingMode(s.overrideScalingMode);
3296 // We don't trigger a traversal here because if no other state is
3297 // changed, we don't want this to cause any more work
3298 }
Marissa Wall61c58622018-07-18 10:12:20 -07003299 if (what & layer_state_t::eTransformChanged) {
3300 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3301 }
3302 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3303 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3304 flags |= eTraversalNeeded;
3305 }
3306 if (what & layer_state_t::eCropChanged) {
3307 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3308 }
Marissa Wall861616d2018-10-22 12:52:23 -07003309 if (what & layer_state_t::eFrameChanged) {
3310 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3311 }
Marissa Wall61c58622018-07-18 10:12:20 -07003312 if (what & layer_state_t::eAcquireFenceChanged) {
3313 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3314 }
3315 if (what & layer_state_t::eDataspaceChanged) {
3316 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3317 }
3318 if (what & layer_state_t::eHdrMetadataChanged) {
3319 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3320 }
3321 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3322 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3323 }
3324 if (what & layer_state_t::eApiChanged) {
3325 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3326 }
3327 if (what & layer_state_t::eSidebandStreamChanged) {
3328 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3329 }
Robert Carr720e5062018-07-30 17:45:14 -07003330 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003331 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003332 layer->setInputInfo(s.inputInfo);
3333 flags |= eTraversalNeeded;
3334 } else {
3335 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3336 }
Robert Carr720e5062018-07-30 17:45:14 -07003337 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003338 if (what & layer_state_t::eMetadataChanged) {
3339 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3340 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003341 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3342 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3343 flags |= eTraversalNeeded;
3344 }
3345 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003346 if (what & layer_state_t::eShadowRadiusChanged) {
3347 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3348 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003349 // This has to happen after we reparent children because when we reparent to null we remove
3350 // child layers from current state and remove its relative z. If the children are reparented in
3351 // the same transaction, then we have to make sure we reparent the children first so we do not
3352 // lose its relative z order.
3353 if (what & layer_state_t::eReparent) {
3354 bool hadParent = layer->hasParent();
3355 if (layer->reparent(s.parentHandleForChild)) {
3356 if (!hadParent) {
3357 mCurrentState.layersSortedByZ.remove(layer);
3358 }
3359 flags |= eTransactionNeeded | eTraversalNeeded;
3360 }
3361 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003362 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003363 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3364 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003365 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3366 }
3367 }
Marissa Wall78b72202019-03-15 14:58:34 -07003368 bool bufferChanged = what & layer_state_t::eBufferChanged;
3369 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3370 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003371 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003372 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003373 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3374 if (success) {
3375 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3376 success = ClientCache::getInstance()
3377 .registerErasedRecipient(s.cachedBuffer,
3378 wp<ClientCache::ErasedRecipient>(this));
3379 if (!success) {
3380 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3381 }
3382 }
Marissa Wall78b72202019-03-15 14:58:34 -07003383 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003384 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003385 } else if (bufferChanged) {
3386 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003387 }
Marissa Wall78b72202019-03-15 14:58:34 -07003388 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003389 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003390 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003391 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003392 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003393 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3394 // Do not put anything that updates layer state or modifies flags after
3395 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003396 return flags;
3397}
3398
chaviw273171b2018-12-26 11:46:30 -08003399uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3400 uint32_t flags = 0;
3401 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3402 flags |= eTraversalNeeded;
3403 }
3404
chaviwa911b102019-02-14 10:18:33 -08003405 if (inputWindowCommands.syncInputWindows) {
3406 flags |= eTraversalNeeded;
3407 }
3408
Vishnu Nairec0ab382019-02-13 15:32:56 -08003409 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003410 return flags;
3411}
3412
chaviwfe94a222019-08-21 13:52:59 -07003413status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3414 sp<IBinder>* outHandle) {
3415 if (!mirrorFromHandle) {
3416 return NAME_NOT_FOUND;
3417 }
3418
3419 sp<Layer> mirrorLayer;
3420 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003421 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003422
3423 {
3424 Mutex::Autolock _l(mStateLock);
3425 mirrorFrom = fromHandle(mirrorFromHandle);
3426 if (!mirrorFrom) {
3427 return NAME_NOT_FOUND;
3428 }
3429
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003430 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3431 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003432 if (result != NO_ERROR) {
3433 return result;
3434 }
3435
3436 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3437 }
3438
3439 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3440}
3441
Marissa Wall2d814fb2019-04-09 18:52:57 +00003442status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3443 uint32_t h, PixelFormat format, uint32_t flags,
3444 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003445 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003446 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3447 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003448 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003449 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003450 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003451 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003452 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003453
Robert Carrc0df3122019-04-11 13:18:21 -07003454 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3455 "Expected only one of parentLayer or parentHandle to be non-null. "
3456 "Programmer error?");
3457
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003458 status_t result = NO_ERROR;
3459
3460 sp<Layer> layer;
3461
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003462 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003463
Evan Roskya1f1e152019-01-24 16:17:46 -08003464 bool primaryDisplayOnly = false;
3465
3466 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3467 // TODO b/64227542
3468 if (metadata.has(METADATA_WINDOW_TYPE)) {
3469 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3470 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003471 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003472 primaryDisplayOnly = true;
3473 }
3474 }
3475
Mathias Agopian3165cc22012-08-08 19:42:09 -07003476 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003477 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003478 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3479 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003480
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003481 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003482 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003483 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003484 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003485 break;
chaviw13fdc492017-06-27 12:40:18 -07003486 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003487 // check if buffer size is set for color layer.
3488 if (w > 0 || h > 0) {
3489 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3490 int(w), int(h));
3491 return BAD_VALUE;
3492 }
3493
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003494 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3495 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003496 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003497 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003498 // check if buffer size is set for container layer.
3499 if (w > 0 || h > 0) {
3500 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3501 int(w), int(h));
3502 return BAD_VALUE;
3503 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003504 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3505 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003506 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003507 default:
3508 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003509 break;
3510 }
3511
Dan Stoza7d89d062015-04-30 13:29:25 -07003512 if (result != NO_ERROR) {
3513 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003514 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003515
Evan Roskya1f1e152019-01-24 16:17:46 -08003516 if (primaryDisplayOnly) {
3517 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003518 }
3519
Robert Carrb89ea9d2018-12-10 13:01:14 -08003520 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003521 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3522 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003523 if (result != NO_ERROR) {
3524 return result;
3525 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003526 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003527
3528 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003529 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003530}
3531
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003532std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3533 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003534
3535 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003536 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003537
Dan Stoza436ccf32018-06-21 12:10:12 -07003538 // Grab the state lock since we're accessing mCurrentState
3539 Mutex::Autolock lock(mStateLock);
3540
Cody Northropbc755282017-03-31 12:00:08 -06003541 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003542 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003543 while (matchFound) {
3544 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003545 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003546 if (layer->getName() == uniqueName) {
3547 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003548 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003549 }
3550 });
3551 }
3552
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003553 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003554 return uniqueName;
3555}
3556
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003557status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003558 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003559 LayerMetadata metadata, PixelFormat& format,
3560 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003561 sp<IGraphicBufferProducer>* gbp,
3562 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003563 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003564 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003565 case PIXEL_FORMAT_TRANSPARENT:
3566 case PIXEL_FORMAT_TRANSLUCENT:
3567 format = PIXEL_FORMAT_RGBA_8888;
3568 break;
3569 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003570 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003571 break;
3572 }
3573
chaviwb4c6e582019-08-16 14:35:07 -07003574 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003575 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003576 args.textureName = getNewTexture();
3577 {
3578 // Grab the SF state lock during this since it's the only safe way to access
3579 // RenderEngine when creating a BufferLayerConsumer
3580 // TODO: Check if this lock is still needed here
3581 Mutex::Autolock lock(mStateLock);
3582 layer = getFactory().createBufferQueueLayer(args);
3583 }
3584
Marissa Wallfd668622018-05-10 10:21:13 -07003585 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003586 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003587 *handle = layer->getHandle();
3588 *gbp = layer->getProducer();
3589 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003591
Marissa Wallfd668622018-05-10 10:21:13 -07003592 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003593 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003594}
3595
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003596status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003597 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003598 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003599 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003600 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003601 args.displayDevice = getDefaultDisplayDevice();
3602 args.textureName = getNewTexture();
3603 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003604 if (outTransformHint) {
3605 *outTransformHint = layer->getTransformHint();
3606 }
Marissa Wall61c58622018-07-18 10:12:20 -07003607 *handle = layer->getHandle();
3608 *outLayer = layer;
3609
3610 return NO_ERROR;
3611}
3612
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003613status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003614 uint32_t h, uint32_t flags, LayerMetadata metadata,
3615 sp<IBinder>* handle, sp<Layer>* outLayer) {
3616 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003617 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003619 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003620}
3621
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003622status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003623 uint32_t w, uint32_t h, uint32_t flags,
3624 LayerMetadata metadata, sp<IBinder>* handle,
3625 sp<Layer>* outLayer) {
3626 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003627 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003628 *handle = (*outLayer)->getHandle();
3629 return NO_ERROR;
3630}
3631
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003632void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003633 mLayersPendingRemoval.add(layer);
3634 mLayersRemoved = true;
3635 setTransactionFlags(eTransactionNeeded);
3636}
3637
Robert Carr695d5282018-12-18 15:27:58 -08003638void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003639{
Robert Carr2e102c92018-10-23 12:11:15 -07003640 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003641 // If a layer has a parent, we allow it to out-live it's handle
3642 // with the idea that the parent holds a reference and will eventually
3643 // be cleaned up. However no one cleans up the top-level so we do so
3644 // here.
3645 if (layer->getParent() == nullptr) {
3646 mCurrentState.layersSortedByZ.remove(layer);
3647 }
3648 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003649
3650 auto it = mLayersByLocalBinderToken.begin();
3651 while (it != mLayersByLocalBinderToken.end()) {
3652 if (it->second == layer) {
3653 it = mLayersByLocalBinderToken.erase(it);
3654 } else {
3655 it++;
3656 }
3657 }
3658
Robert Carr695d5282018-12-18 15:27:58 -08003659 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003660}
3661
Mathias Agopianb60314a2012-04-10 22:09:54 -07003662// ---------------------------------------------------------------------------
3663
Andy McFadden13a082e2012-08-24 10:16:42 -07003664void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003665 const auto display = getDefaultDisplayDeviceLocked();
3666 if (!display) return;
3667
3668 const sp<IBinder> token = display->getDisplayToken().promote();
3669 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003670
Jesse Hall01e29052013-02-19 16:13:35 -08003671 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003672 Vector<ComposerState> state;
3673 Vector<DisplayState> displays;
3674 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003675 d.what = DisplayState::eDisplayProjectionChanged |
3676 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003677 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003678 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003679 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003680 d.frame.makeInvalid();
3681 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003682 d.width = 0;
3683 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003684 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003685 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3686 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003687
Dominik Laskowskie9774092018-12-11 10:04:24 -08003688 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003689
Dominik Laskowski83b88212018-12-11 13:34:06 -08003690 const nsecs_t vsyncPeriod = getVsyncPeriod();
3691 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003692
Brian Andersond0010582017-03-07 13:20:31 -08003693 // Use phase of 0 since phase is not known.
3694 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003695 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003696 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003697}
3698
3699void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003700 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003701 postMessageAsync(
3702 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003703}
3704
Ady Abraham27c70212019-06-11 10:52:26 -07003705void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3706 if (mHWCVsyncState != enabled) {
3707 getHwComposer().setVsyncEnabled(displayId, enabled);
3708 mHWCVsyncState = enabled;
3709 }
3710}
3711
Dominik Laskowskie9774092018-12-11 10:04:24 -08003712void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003713 if (display->isVirtual()) {
3714 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715 return;
3716 }
3717
Dominik Laskowski075d3172018-05-24 15:50:06 -07003718 const auto displayId = display->getId();
3719 LOG_ALWAYS_FATAL_IF(!displayId);
3720
Dominik Laskowski34157762018-10-31 13:07:19 -07003721 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003722
3723 int currentMode = display->getPowerMode();
3724 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003725 return;
3726 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003727
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003728 display->setPowerMode(mode);
3729
Lloyd Pique4dccc412018-01-22 17:21:36 -08003730 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003731 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003732 }
3733
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003735 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003736 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003737 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003738 mScheduler->onScreenAcquired(mAppConnectionHandle);
3739 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003740 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003741
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003742 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003743 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003744 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003745
3746 struct sched_param param = {0};
3747 param.sched_priority = 1;
3748 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3749 ALOGW("Couldn't set SCHED_FIFO on display on");
3750 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003751 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003752 // Turn off the display
3753 struct sched_param param = {0};
3754 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3755 ALOGW("Couldn't set SCHED_OTHER on display off");
3756 }
3757
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003758 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003759 mScheduler->disableHardwareVsync(true);
3760 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003761 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003762
Ady Abraham27c70212019-06-11 10:52:26 -07003763 // Make sure HWVsync is disabled before turning off the display
3764 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3765
Dominik Laskowski075d3172018-05-24 15:50:06 -07003766 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003767 mVisibleRegionsDirty = true;
3768 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003769 } else if (mode == HWC_POWER_MODE_DOZE ||
3770 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003771 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003772 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003773 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003774 mScheduler->onScreenAcquired(mAppConnectionHandle);
3775 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003776 }
3777 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3778 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003779 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003780 mScheduler->disableHardwareVsync(true);
3781 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003782 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003783 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003784 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003785 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003786 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003787 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003788
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003789 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003790 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003791 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003792 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003793 }
3794
Dominik Laskowski34157762018-10-31 13:07:19 -07003795 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003796}
3797
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003798void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003799 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003800 const auto display = getDisplayDevice(displayToken);
3801 if (!display) {
3802 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3803 displayToken.get());
3804 } else if (display->isVirtual()) {
3805 ALOGW("Attempt to set power mode %d for virtual display", mode);
3806 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003807 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003808 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003809 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003810}
3811
3812// ---------------------------------------------------------------------------
3813
Dominik Laskowskic2867142019-01-21 11:33:38 -08003814status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3815 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003816 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003817
Mathias Agopianbd115332013-04-18 16:41:04 -07003818 IPCThreadState* ipc = IPCThreadState::self();
3819 const int pid = ipc->getCallingPid();
3820 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003821
Mathias Agopianbd115332013-04-18 16:41:04 -07003822 if ((uid != AID_SHELL) &&
3823 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003824 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3825 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003826 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003827 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003828 // (this would indicate SF is stuck, but we want to be able to
3829 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003830 status_t err = mStateLock.timedLock(s2ns(1));
3831 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003832 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003833 StringAppendF(&result,
3834 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3835 "(no locks held)\n",
3836 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003837 }
3838
Dominik Laskowskic2867142019-01-21 11:33:38 -08003839 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003840 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003841 {"--dispsync"s,
3842 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003843 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003844 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3845 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3846 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3847 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3848 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3849 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003850 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003851 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3852 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853
Dominik Laskowskic2867142019-01-21 11:33:38 -08003854 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003855
Dominik Laskowski46470112019-08-02 13:13:11 -07003856 const auto it = dumpers.find(flag);
3857 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003858 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003859 } else if (!asProto) {
3860 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003861 }
3862
Mathias Agopian9795c422009-08-26 16:36:26 -07003863 if (locked) {
3864 mStateLock.unlock();
3865 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003866
Dominik Laskowski46470112019-08-02 13:13:11 -07003867 if (it == dumpers.end()) {
3868 const LayersProto layersProto = dumpProtoFromMainThread();
3869 if (asProto) {
3870 result.append(layersProto.SerializeAsString());
3871 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003872 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003873 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3874 result.append(LayerProtoParser::layerTreeToString(layerTree));
3875 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003876 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003877 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003878 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003880 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003881 return NO_ERROR;
3882}
3883
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003884status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3885 if (asProto && mTracing.isEnabled()) {
3886 mTracing.writeToFileAsync();
3887 }
3888
3889 return doDump(fd, DumpArgs(), asProto);
3890}
3891
Dominik Laskowskic2867142019-01-21 11:33:38 -08003892void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003893 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003894 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003895}
3896
Dominik Laskowskic2867142019-01-21 11:33:38 -08003897void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003898 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003899
Dominik Laskowskic2867142019-01-21 11:33:38 -08003900 if (args.size() > 1) {
3901 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003902 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003904 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003905 }
Robert Carr2047fae2016-11-28 14:09:09 -08003906 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003907 } else {
3908 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003909 }
3910}
3911
Dominik Laskowskic2867142019-01-21 11:33:38 -08003912void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003913 const bool clearAll = args.size() < 2;
3914 const auto name = clearAll ? String8() : String8(args[1]);
3915
Robert Carr2047fae2016-11-28 14:09:09 -08003916 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003917 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003918 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003919 }
Robert Carr2047fae2016-11-28 14:09:09 -08003920 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003921
Svetoslavd85084b2014-03-20 10:28:31 -07003922 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003923}
3924
Dominik Laskowskic2867142019-01-21 11:33:38 -08003925void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3926 mTimeStats->parseArgs(asProto, args, result);
3927}
3928
Jamie Gennis6547ff42013-07-16 20:12:42 -07003929// This should only be called from the main thread. Otherwise it would need
3930// the lock and should use mCurrentState rather than mDrawingState.
3931void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003932 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003933 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003934 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003935
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003936 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07003937}
3938
Yiwei Zhang5434a782018-12-05 18:06:32 -08003939void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003940 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003941
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003942 if (isLayerTripleBufferingDisabled())
3943 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003944
Yiwei Zhang5434a782018-12-05 18:06:32 -08003945 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3946 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3947 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3948 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3949 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3950 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003951 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003952}
3953
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003954void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003955 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003956
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003957 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003958 result.append("\n");
3959
Ana Krulec757f63a2019-01-25 10:46:18 -08003960 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003961 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003962 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003963 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003964
Ady Abraham42b3beb2019-07-09 18:09:52 -07003965 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003966 for (int32_t configId : mAllowedDisplayConfigs) {
3967 StringAppendF(&result, "%" PRIu32 " Hz, ",
3968 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003969 }
Ana Krulec234bb162019-11-10 22:55:55 +01003970 StringAppendF(&result,
3971 "DesiredDisplayConfigSpecs: default config ID: %" PRIu32
3972 ", min: %.2f Hz, max: %.2f Hz",
3973 mDesiredDisplayConfigSpecs.defaultModeId,
3974 mDesiredDisplayConfigSpecs.minRefreshRate,
3975 mDesiredDisplayConfigSpecs.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003976 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3977 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003978
Ana Krulecc2870422019-01-29 19:00:58 -08003979 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003980}
3981
Yiwei Zhang5434a782018-12-05 18:06:32 -08003982void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3983 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003984 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3985 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003986 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003987 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003988 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003989 }
David Sodman4a36e932017-11-07 14:29:47 -08003990 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003991 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003992 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003993 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3994 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003995}
3996
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003997void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
3998 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003999 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4000 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004001 for (const auto& segment : history) {
4002 if (!segment.usedThirdBuffer) {
4003 stats.twoBufferTime += segment.totalTime;
4004 }
4005 if (segment.occupancyAverage < 1.0f) {
4006 stats.doubleBufferedTime += segment.totalTime;
4007 } else if (segment.occupancyAverage < 2.0f) {
4008 stats.tripleBufferedTime += segment.totalTime;
4009 }
4010 ++stats.numSegments;
4011 stats.totalTime += segment.totalTime;
4012 }
4013}
4014
Yiwei Zhang5434a782018-12-05 18:06:32 -08004015void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4016 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004017
4018 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4019 const size_t count = currentLayers.size();
4020 for (size_t i=0 ; i<count ; i++) {
4021 currentLayers[i]->dumpFrameEvents(result);
4022 }
4023}
4024
Yiwei Zhang5434a782018-12-05 18:06:32 -08004025void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004026 result.append("Buffering stats:\n");
4027 result.append(" [Layer name] <Active time> <Two buffer> "
4028 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004029 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004030 typedef std::tuple<std::string, float, float, float> BufferTuple;
4031 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004032 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004033 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004034 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004035 if (stats.numSegments == 0) {
4036 continue;
4037 }
4038 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4039 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4040 stats.totalTime;
4041 float doubleBufferRatio = static_cast<float>(
4042 stats.doubleBufferedTime) / stats.totalTime;
4043 float tripleBufferRatio = static_cast<float>(
4044 stats.tripleBufferedTime) / stats.totalTime;
4045 sorted.insert({activeTime, {name, twoBufferRatio,
4046 doubleBufferRatio, tripleBufferRatio}});
4047 }
4048 for (const auto& sortedPair : sorted) {
4049 float activeTime = sortedPair.first;
4050 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004051 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4052 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004053 }
4054 result.append("\n");
4055}
4056
Yiwei Zhang5434a782018-12-05 18:06:32 -08004057void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004058 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004059 const auto displayId = display->getId();
4060 if (!displayId) {
4061 continue;
4062 }
4063 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004064 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004065 continue;
4066 }
4067
Yiwei Zhang5434a782018-12-05 18:06:32 -08004068 StringAppendF(&result,
4069 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4070 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004071 uint8_t port;
4072 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004073 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004074 result.append("no identification data\n");
4075 continue;
4076 }
4077
4078 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004079 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004080 continue;
4081 }
4082
4083 const auto edid = parseEdid(data);
4084 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004085 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004086 continue;
4087 }
4088
Yiwei Zhang5434a782018-12-05 18:06:32 -08004089 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004090 result.append(edid->displayName.data(), edid->displayName.length());
4091 result.append("\"\n");
4092 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004093}
4094
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004095void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4096 std::string& result) const {
4097 hwc2_display_t hwcDisplayId;
4098 uint8_t port;
4099 DisplayIdentificationData data;
4100
4101 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4102 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4103 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4104 }
4105}
4106
Yiwei Zhang5434a782018-12-05 18:06:32 -08004107void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004108 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004109 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4110 StringAppendF(&result, "DisplayColorSetting: %s\n",
4111 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004112
4113 // TODO: print out if wide-color mode is active or not
4114
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004115 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004116 const auto displayId = display->getId();
4117 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004118 continue;
4119 }
4120
Yiwei Zhang5434a782018-12-05 18:06:32 -08004121 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004122 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004123 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004124 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004125 }
4126
Lloyd Pique32cbe282018-10-19 13:09:22 -07004127 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004128 StringAppendF(&result, " Current color mode: %s (%d)\n",
4129 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004130 }
4131 result.append("\n");
4132}
4133
Vishnu Nair8406fd72019-07-30 11:29:31 -07004134LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004135 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004136 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004137 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004138 layer->writeToProtoDrawingState(layerProto, traceFlags);
4139 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004140 });
4141
4142 return layersProto;
4143}
4144
Vishnu Nair0f085c62019-08-30 08:49:12 -07004145void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4146 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4147 // it.
4148 LayerProto* rootProto = layersProto.add_layers();
4149 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4150 rootProto->set_id(offscreenRootLayerId);
4151 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004152 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004153
4154 for (Layer* offscreenLayer : mOffscreenLayers) {
4155 // Add layer as child of the fake root
4156 rootProto->add_children(offscreenLayer->sequence);
4157
4158 // Add layer
4159 LayerProto* layerProto = layersProto.add_layers();
4160 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4161 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4162 traceFlags);
4163 layerProto->set_parent(offscreenRootLayerId);
4164
4165 // Add children
4166 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4167 if (layer == offscreenLayer) {
4168 return;
4169 }
4170 LayerProto* childProto = layersProto.add_layers();
4171 layer->writeToProtoDrawingState(childProto, traceFlags);
4172 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4173 });
4174 }
4175}
4176
Vishnu Nair8406fd72019-07-30 11:29:31 -07004177LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4178 LayersProto layersProto;
4179 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4180 return layersProto;
4181}
4182
Vishnu Nair0f085c62019-08-30 08:49:12 -07004183void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4184 result.append("Offscreen Layers:\n");
4185 postMessageSync(new LambdaMessage([&]() {
4186 for (Layer* offscreenLayer : mOffscreenLayers) {
4187 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4188 layer->dumpCallingUidPid(result);
4189 });
4190 }
4191 }));
4192}
4193
Dominik Laskowskic2867142019-01-21 11:33:38 -08004194void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4195 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004196 Colorizer colorizer(colorize);
4197
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004198 // figure out if we're stuck somewhere
4199 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004200 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4202
4203 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004204 * Dump library configuration.
4205 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004206
4207 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004208 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004209 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004210 appendSfConfigString(result);
4211 appendUiConfigString(result);
4212 appendGuiConfigString(result);
4213 result.append("\n");
4214
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004215 result.append("\nDisplay identification data:\n");
4216 dumpDisplayIdentificationData(result);
4217
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004218 result.append("\nWide-Color information:\n");
4219 dumpWideColorInfo(result);
4220
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004221 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004222 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004223 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004224 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004225 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004226
Andy McFadden41d67d72014-04-25 16:58:34 -07004227 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004228 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004229 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004230 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004231 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004232
Dan Stozab90cf072015-03-05 11:05:59 -08004233 dumpStaticScreenStats(result);
4234 result.append("\n");
4235
Alec Mouri40189b02019-03-05 15:07:54 -08004236 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4237 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4238 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004239
Dan Stozae77c7662016-05-13 11:37:28 -07004240 dumpBufferingStats(result);
4241
Andy McFadden4803b742012-09-24 19:07:20 -07004242 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004243 * Dump the visible layer list
4244 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004245 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004246 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004247 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4248 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004249 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004250
Chia-I Wu2f884132018-09-13 15:17:58 -07004251 {
Lloyd Pique207def92019-02-28 16:09:52 -08004252 StringAppendF(&result, "Composition layers\n");
4253 mDrawingState.traverseInZOrder([&](Layer* layer) {
4254 auto compositionLayer = layer->getCompositionLayer();
4255 if (compositionLayer) compositionLayer->dump(result);
4256 });
4257 }
4258
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004260 * Dump Display state
4261 */
4262
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004263 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004264 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004265 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004266 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004267 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004268 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004269 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004270
4271 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004272 * Dump CompositionEngine state
4273 */
4274
4275 mCompositionEngine->dump(result);
4276
4277 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 * Dump SurfaceFlinger global state
4279 */
4280
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004281 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004282 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004283 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004285 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004286
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004287 DebugEGLImageTracker::getInstance()->dump(result);
4288
Dominik Laskowski075d3172018-05-24 15:50:06 -07004289 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004290 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4291 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004292 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4293 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004294 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 StringAppendF(&result,
4296 " transaction-flags : %08x\n"
4297 " gpu_to_cpu_unsupported : %d\n",
4298 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004299
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004300 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004301 displayId && getHwComposer().isConnected(*displayId)) {
4302 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004303 StringAppendF(&result,
4304 " refresh-rate : %f fps\n"
4305 " x-dpi : %f\n"
4306 " y-dpi : %f\n",
4307 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4308 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004309 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004310
Yiwei Zhang5434a782018-12-05 18:06:32 -08004311 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312
Dan Stozae22aec72016-08-01 13:20:59 -07004313 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004314 * Tracing state
4315 */
4316 mTracing.dump(result);
4317 result.append("\n");
4318
4319 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004320 * HWC layer minidump
4321 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004322 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004323 const auto displayId = display->getId();
4324 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004325 continue;
4326 }
4327
Yiwei Zhang5434a782018-12-05 18:06:32 -08004328 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004329 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004330 const sp<DisplayDevice> displayDevice = display;
4331 mCurrentState.traverseInZOrder(
4332 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004333 result.append("\n");
4334 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335
4336 /*
4337 * Dump HWComposer state
4338 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004339 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004340 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004341 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004342 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004343 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004344 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004345
4346 /*
4347 * Dump gralloc state
4348 */
4349 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4350 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004351
4352 /*
4353 * Dump VrFlinger state if in use.
4354 */
4355 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4356 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004357 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004358 result.append("\n");
4359 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004360
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004361 result.append(mTimeStats->miniDump());
4362 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004363}
4364
Chia-I Wu28f320b2018-05-03 11:02:56 -07004365void SurfaceFlinger::updateColorMatrixLocked() {
4366 mat4 colorMatrix;
4367 if (mGlobalSaturationFactor != 1.0f) {
4368 // Rec.709 luma coefficients
4369 float3 luminance{0.213f, 0.715f, 0.072f};
4370 luminance *= 1.0f - mGlobalSaturationFactor;
4371 mat4 saturationMatrix = mat4(
4372 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4373 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4374 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4375 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4376 );
4377 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4378 } else {
4379 colorMatrix = mClientColorMatrix * mDaltonizer();
4380 }
4381
4382 if (mCurrentState.colorMatrix != colorMatrix) {
4383 mCurrentState.colorMatrix = colorMatrix;
4384 mCurrentState.colorMatrixChanged = true;
4385 setTransactionFlags(eTransactionNeeded);
4386 }
4387}
4388
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004389status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004390#pragma clang diagnostic push
4391#pragma clang diagnostic error "-Wswitch-enum"
4392 switch (static_cast<ISurfaceComposerTag>(code)) {
4393 // These methods should at minimum make sure that the client requested
4394 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004395 case BOOT_FINISHED:
4396 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004397 case CREATE_DISPLAY:
4398 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004399 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004400 case GET_ANIMATION_FRAME_STATS:
4401 case GET_HDR_CAPABILITIES:
4402 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004403 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004404 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec0782b882019-10-15 17:34:54 -07004405 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004406 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004407 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004408 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004409 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004410 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004411 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004412 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004413 case NOTIFY_POWER_HINT:
4414 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004415 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4416 IPCThreadState* ipc = IPCThreadState::self();
4417 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4418 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004419 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004420 }
Robert Carr1db73f62016-12-21 12:58:51 -08004421 return OK;
4422 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004423 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004424 IPCThreadState* ipc = IPCThreadState::self();
4425 const int pid = ipc->getCallingPid();
4426 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004427 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4428 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004429 return PERMISSION_DENIED;
4430 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004431 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004432 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004433 // Used by apps to hook Choreographer to SurfaceFlinger.
4434 case CREATE_DISPLAY_EVENT_CONNECTION:
4435 // The following calls are currently used by clients that do not
4436 // request necessary permissions. However, they do not expose any secret
4437 // information, so it is OK to pass them.
4438 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004439 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004440 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004441 case GET_PHYSICAL_DISPLAY_IDS:
4442 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004443 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004444 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004445 case GET_DISPLAY_CONFIGS:
4446 case GET_DISPLAY_STATS:
4447 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4448 // Calling setTransactionState is safe, because you need to have been
4449 // granted a reference to Client* and Handle* to do anything with it.
4450 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004451 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004452 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004453 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004454 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004455 case IS_WIDE_COLOR_DISPLAY:
4456 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4457 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004458 return OK;
4459 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004460 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004461 case CAPTURE_SCREEN:
4462 case ADD_REGION_SAMPLING_LISTENER:
4463 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004464 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004465 IPCThreadState* ipc = IPCThreadState::self();
4466 const int pid = ipc->getCallingPid();
4467 const int uid = ipc->getCallingUid();
4468 if ((uid != AID_GRAPHICS) &&
4469 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4470 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4471 return PERMISSION_DENIED;
4472 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004473 return OK;
4474 }
4475 // The following codes are deprecated and should never be allowed to access SF.
4476 case CONNECT_DISPLAY_UNUSED:
4477 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4478 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4479 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004480 }
chaviw93df2ea2019-04-30 16:45:12 -07004481 case CAPTURE_SCREEN_BY_ID: {
4482 IPCThreadState* ipc = IPCThreadState::self();
4483 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004484 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004485 return OK;
4486 }
4487 return PERMISSION_DENIED;
4488 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004489 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004490
4491 // These codes are used for the IBinder protocol to either interrogate the recipient
4492 // side of the transaction for its canonical interface descriptor or to dump its state.
4493 // We let them pass by default.
4494 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4495 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4496 code == IBinder::SYSPROPS_TRANSACTION) {
4497 return OK;
4498 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004499 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004500 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004501 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004502 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4503 return OK;
4504 }
4505 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4506 return PERMISSION_DENIED;
4507#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004508}
4509
Ana Krulec13be8ad2018-08-21 02:43:56 +00004510status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4511 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004512 status_t credentialCheck = CheckTransactCodeCredentials(code);
4513 if (credentialCheck != OK) {
4514 return credentialCheck;
4515 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004516
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004517 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4518 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004519 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004520 IPCThreadState* ipc = IPCThreadState::self();
4521 const int uid = ipc->getCallingUid();
4522 if (CC_UNLIKELY(uid != AID_SYSTEM
4523 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004524 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004525 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004526 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 return PERMISSION_DENIED;
4528 }
4529 int n;
4530 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004531 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004532 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 return NO_ERROR;
4534 case 1002: // SHOW_UPDATES
4535 n = data.readInt32();
4536 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004537 invalidateHwcGeometry();
4538 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004539 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004540 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004541 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004542 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004543 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004544 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004545 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004546 setTransactionFlags(
4547 eTransactionNeeded|
4548 eDisplayTransactionNeeded|
4549 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004550 return NO_ERROR;
4551 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004552 case 1006:{ // send empty update
4553 signalRefresh();
4554 return NO_ERROR;
4555 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004556 case 1008: // toggle use of hw composer
4557 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004558 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004559 invalidateHwcGeometry();
4560 repaintEverything();
4561 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004562 case 1009: // toggle use of transform hint
4563 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004564 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004565 invalidateHwcGeometry();
4566 repaintEverything();
4567 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004568 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004569 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 reply->writeInt32(0);
4571 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004572 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004573 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004574 return NO_ERROR;
4575 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004576 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004577 if (!display) {
4578 return NAME_NOT_FOUND;
4579 }
4580
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004581 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004582 return NO_ERROR;
4583 }
4584 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004585 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004586 // daltonize
4587 n = data.readInt32();
4588 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004589 case 1:
4590 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4591 break;
4592 case 2:
4593 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4594 break;
4595 case 3:
4596 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4597 break;
4598 default:
4599 mDaltonizer.setType(ColorBlindnessType::None);
4600 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004601 }
4602 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004603 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004604 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004605 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004606 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004607
4608 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004609 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004610 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004611 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004612 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004613 // apply a color matrix
4614 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004615 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004616 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004617 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004618 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004619 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004620 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004621 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004622 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004623 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004624 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004625
4626 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4627 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004628 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004629 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4630 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4631 }
4632
Chia-I Wu28f320b2018-05-03 11:02:56 -07004633 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 return NO_ERROR;
4635 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004636 case 1016: { // Unused.
4637 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004638 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004639 case 1017: {
4640 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004641 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004642 return NO_ERROR;
4643 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004644 case 1018: { // Modify Choreographer's phase offset
4645 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004646 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004647 return NO_ERROR;
4648 }
4649 case 1019: { // Modify SurfaceFlinger's phase offset
4650 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004651 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004652 return NO_ERROR;
4653 }
Irvel468051e2016-06-13 16:44:44 -07004654 case 1020: { // Layer updates interceptor
4655 n = data.readInt32();
4656 if (n) {
4657 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004658 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004659 }
4660 else{
4661 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004662 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004663 }
4664 return NO_ERROR;
4665 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004666 case 1021: { // Disable HWC virtual displays
4667 n = data.readInt32();
4668 mUseHwcVirtualDisplays = !n;
4669 return NO_ERROR;
4670 }
Romain Guy0147a172017-06-01 13:53:56 -07004671 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004672 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004673 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004674
Chia-I Wu28f320b2018-05-03 11:02:56 -07004675 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004676 return NO_ERROR;
4677 }
Romain Guy54f154a2017-10-24 21:40:32 +01004678 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004679 int32_t colorMode;
4680
Chia-I Wu0d711262018-05-21 15:19:35 -07004681 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004682 if (data.readInt32(&colorMode) == NO_ERROR) {
4683 mForceColorMode = static_cast<ColorMode>(colorMode);
4684 }
Romain Guy54f154a2017-10-24 21:40:32 +01004685 invalidateHwcGeometry();
4686 repaintEverything();
4687 return NO_ERROR;
4688 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004689 // Deprecate, use 1030 to check whether the device is color managed.
4690 case 1024: {
4691 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004692 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004693 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004694 n = data.readInt32();
4695 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004696 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004697 Mutex::Autolock lock(mStateLock);
4698 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004699 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004700 reply->writeInt32(NO_ERROR);
4701 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004702 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004703 bool writeFile = false;
4704 {
4705 Mutex::Autolock lock(mStateLock);
4706 mTracingEnabledChanged = true;
4707 writeFile = mTracing.disable();
4708 }
4709
4710 if (writeFile) {
4711 reply->writeInt32(mTracing.writeToFile());
4712 } else {
4713 reply->writeInt32(NO_ERROR);
4714 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004715 }
4716 return NO_ERROR;
4717 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004718 case 1026: { // Get layer tracing status
4719 reply->writeBool(mTracing.isEnabled());
4720 return NO_ERROR;
4721 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004722 // Is a DisplayColorSetting supported?
4723 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004724 const auto display = getDefaultDisplayDevice();
4725 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004726 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004727 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004728
4729 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4730 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004731 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004732 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004733 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004734 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004735 reply->writeBool(true);
4736 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004737 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004738 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004739 break;
4740 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004741 reply->writeBool(
4742 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004743 break;
4744 }
4745 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004746 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004747 // Is VrFlinger active?
4748 case 1028: {
4749 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004750 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004751 return NO_ERROR;
4752 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004753 // Set buffer size for SF tracing (value in KB)
4754 case 1029: {
4755 n = data.readInt32();
4756 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4757 ALOGW("Invalid buffer size: %d KB", n);
4758 reply->writeInt32(BAD_VALUE);
4759 return BAD_VALUE;
4760 }
4761
4762 ALOGD("Updating trace buffer to %d KB", n);
4763 mTracing.setBufferSize(n * 1024);
4764 reply->writeInt32(NO_ERROR);
4765 return NO_ERROR;
4766 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004767 // Is device color managed?
4768 case 1030: {
4769 reply->writeBool(useColorManagement);
4770 return NO_ERROR;
4771 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004772 // Override default composition data space
4773 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4774 // && adb shell stop zygote && adb shell start zygote
4775 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4776 // adb shell stop zygote && adb shell start zygote
4777 case 1031: {
4778 Mutex::Autolock _l(mStateLock);
4779 n = data.readInt32();
4780 if (n) {
4781 n = data.readInt32();
4782 if (n) {
4783 Dataspace dataspace = static_cast<Dataspace>(n);
4784 if (!validateCompositionDataspace(dataspace)) {
4785 return BAD_VALUE;
4786 }
4787 mDefaultCompositionDataspace = dataspace;
4788 }
4789 n = data.readInt32();
4790 if (n) {
4791 Dataspace dataspace = static_cast<Dataspace>(n);
4792 if (!validateCompositionDataspace(dataspace)) {
4793 return BAD_VALUE;
4794 }
4795 mWideColorGamutCompositionDataspace = dataspace;
4796 }
4797 } else {
4798 // restore composition data space.
4799 mDefaultCompositionDataspace = defaultCompositionDataspace;
4800 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4801 }
4802 return NO_ERROR;
4803 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004804 // Set trace flags
4805 case 1033: {
4806 n = data.readUint32();
4807 ALOGD("Updating trace flags to 0x%x", n);
4808 mTracing.setTraceFlags(n);
4809 reply->writeInt32(NO_ERROR);
4810 return NO_ERROR;
4811 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004812 case 1034: {
4813 // TODO(b/129297325): expose this via developer menu option
4814 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004815 if (n && !mRefreshRateOverlay &&
4816 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004817 RefreshRateType type;
4818 {
4819 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4820 type = mDesiredActiveConfig.type;
4821 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004822 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004823 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004824 } else if (!n) {
4825 mRefreshRateOverlay.reset();
4826 }
4827 return NO_ERROR;
4828 }
Ady Abraham34392f72019-04-10 11:29:27 -07004829 case 1035: {
4830 n = data.readInt32();
4831 mDebugDisplayConfigSetByBackdoor = false;
4832 if (n >= 0) {
4833 const auto displayToken = getInternalDisplayToken();
4834 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4835 if (result != NO_ERROR) {
4836 return result;
4837 }
4838 mDebugDisplayConfigSetByBackdoor = true;
4839 }
4840 return NO_ERROR;
4841 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004842 }
4843 }
4844 return err;
4845}
4846
Steven Thomas6d8110b2017-08-31 18:24:21 -07004847void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004848 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004849 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004850}
4851
Ana Krulec7d1d6832018-12-27 11:10:09 -08004852void SurfaceFlinger::repaintEverythingForHWC() {
4853 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004854 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004855}
4856
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004857// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4858class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004859public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004860 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4861 ~WindowDisconnector() {
4862 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004863 }
4864
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004865private:
4866 ANativeWindow* mWindow;
4867 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004868};
4869
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004870status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004871 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4872 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004873 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004874 uint32_t reqWidth, uint32_t reqHeight,
4875 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004876 ISurfaceComposer::Rotation rotation,
4877 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004878 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004879
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004880 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004881
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004882 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4883
Chia-I Wu20261cb2018-08-23 12:55:44 -07004884 sp<DisplayDevice> display;
4885 {
4886 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004887
Chia-I Wu20261cb2018-08-23 12:55:44 -07004888 display = getDisplayDeviceLocked(displayToken);
4889 if (!display) return BAD_VALUE;
4890
Chia-I Wucb023152018-08-28 12:57:23 -07004891 // set the requested width/height to the logical display viewport size
4892 // by default
4893 if (reqWidth == 0 || reqHeight == 0) {
4894 reqWidth = uint32_t(display->getViewport().width());
4895 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004896 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004897 }
4898
Peiyong Lin0e003c92018-09-17 11:09:51 -07004899 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004900 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004901
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004902 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4903 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004904 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004905 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004906}
4907
chaviw93df2ea2019-04-30 16:45:12 -07004908static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4909 switch (colorMode) {
4910 case ColorMode::DISPLAY_P3:
4911 case ColorMode::BT2100_PQ:
4912 case ColorMode::BT2100_HLG:
4913 case ColorMode::DISPLAY_BT2020:
4914 return Dataspace::DISPLAY_P3;
4915 default:
4916 return Dataspace::V0_SRGB;
4917 }
4918}
4919
4920const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4921 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4922 if (displayToken) {
4923 return getDisplayDeviceLocked(displayToken);
4924 }
4925 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4926 // may not have a displayId.
4927 for (const auto& [token, display] : mDisplays) {
4928 if (display->getLayerStack() == displayOrLayerStack) {
4929 return display;
4930 }
4931 }
4932 return nullptr;
4933}
4934
4935status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4936 sp<GraphicBuffer>* outBuffer) {
4937 sp<DisplayDevice> display;
4938 uint32_t width;
4939 uint32_t height;
4940 ui::Transform::orientation_flags captureOrientation;
4941 {
4942 Mutex::Autolock _l(mStateLock);
4943 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4944 if (!display) {
4945 return BAD_VALUE;
4946 }
4947
4948 width = uint32_t(display->getViewport().width());
4949 height = uint32_t(display->getViewport().height());
4950
4951 captureOrientation = fromSurfaceComposerRotation(
4952 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004953 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4954 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4955 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4956 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4957 }
chaviw93df2ea2019-04-30 16:45:12 -07004958 *outDataspace =
4959 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4960 }
4961
4962 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4963 false /* captureSecureLayers */);
4964
4965 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4966 std::placeholders::_1);
4967 bool ignored = false;
4968 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4969 false /* useIdentityTransform */,
4970 ignored /* outCapturedSecureLayers */);
4971}
4972
Robert Carr866455f2019-04-02 16:28:26 -07004973status_t SurfaceFlinger::captureLayers(
4974 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4975 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4976 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4977 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004978 ATRACE_CALL();
4979
4980 class LayerRenderArea : public RenderArea {
4981 public:
Robert Carr578038f2018-03-09 12:25:24 -08004982 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004983 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4984 bool childrenOnly)
4985 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004986 mLayer(layer),
4987 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004988 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004989 mFlinger(flinger),
4990 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004991 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004992 Rect getBounds() const override {
4993 const Layer::State& layerState(mLayer->getDrawingState());
4994 return mLayer->getBufferSize(layerState);
4995 }
Marissa Wall61c58622018-07-18 10:12:20 -07004996 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004997 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004998 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004999 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005000 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005001 }
chaviwa76b2712017-09-20 12:02:26 -07005002 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005003 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005004 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005005 Rect getSourceCrop() const override {
5006 if (mCrop.isEmpty()) {
5007 return getBounds();
5008 } else {
5009 return mCrop;
5010 }
5011 }
Robert Carr578038f2018-03-09 12:25:24 -08005012 class ReparentForDrawing {
5013 public:
5014 const sp<Layer>& oldParent;
5015 const sp<Layer>& newParent;
5016
Vishnu Nair4351ad52019-02-11 14:13:02 -08005017 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5018 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005019 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005020 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005021 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5022 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005023 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005024 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005025 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005026 };
5027
5028 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005029 const Rect sourceCrop = getSourceCrop();
5030 // no need to check rotation because there is none
5031 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5032 sourceCrop.height() != getReqHeight();
5033
Robert Carr578038f2018-03-09 12:25:24 -08005034 if (!mChildrenOnly) {
5035 mTransform = mLayer->getTransform().inverse();
5036 drawLayers();
5037 } else {
5038 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005039 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5040 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005041 // In the "childrenOnly" case we reparent the children to a screenshot
5042 // layer which has no properties set and which does not draw.
5043 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005044 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5045 "Screenshot Parent"s, w, h, 0,
5046 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005047
Vishnu Nair4351ad52019-02-11 14:13:02 -08005048 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005049 drawLayers();
5050 }
5051 }
chaviwa76b2712017-09-20 12:02:26 -07005052
chaviwa76b2712017-09-20 12:02:26 -07005053 private:
chaviw7206d492017-11-10 16:16:12 -08005054 const sp<Layer> mLayer;
5055 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005056
Peiyong Linefefaac2018-08-17 12:27:51 -07005057 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005058 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005059
5060 SurfaceFlinger* mFlinger;
5061 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005062 };
5063
Robert Carrc0df3122019-04-11 13:18:21 -07005064 int reqWidth = 0;
5065 int reqHeight = 0;
5066 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005067 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005068 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005069
Robert Carrc0df3122019-04-11 13:18:21 -07005070 {
5071 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005072
Robert Carrc0df3122019-04-11 13:18:21 -07005073 parent = fromHandle(layerHandleBinder);
5074 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5075 ALOGE("captureLayers called with an invalid or removed parent");
5076 return NAME_NOT_FOUND;
5077 }
5078
5079 const int uid = IPCThreadState::self()->getCallingUid();
5080 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5081 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5082 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5083 return PERMISSION_DENIED;
5084 }
5085
5086 if (sourceCrop.width() <= 0) {
5087 crop.left = 0;
5088 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5089 }
5090
5091 if (sourceCrop.height() <= 0) {
5092 crop.top = 0;
5093 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5094 }
5095 reqWidth = crop.width() * frameScale;
5096 reqHeight = crop.height() * frameScale;
5097
5098 for (const auto& handle : excludeHandles) {
5099 sp<Layer> excludeLayer = fromHandle(handle);
5100 if (excludeLayer != nullptr) {
5101 excludeLayers.emplace(excludeLayer);
5102 } else {
5103 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5104 return NAME_NOT_FOUND;
5105 }
5106 }
5107 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005108
Chia-I Wu20261cb2018-08-23 12:55:44 -07005109 // really small crop or frameScale
5110 if (reqWidth <= 0) {
5111 reqWidth = 1;
5112 }
5113 if (reqHeight <= 0) {
5114 reqHeight = 1;
5115 }
5116
Robert Carr866455f2019-04-02 16:28:26 -07005117 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5118 auto traverseLayers = [parent, childrenOnly,
5119 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005120 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5121 if (!layer->isVisible()) {
5122 return;
Robert Carr578038f2018-03-09 12:25:24 -08005123 } else if (childrenOnly && layer == parent.get()) {
5124 return;
chaviwa76b2712017-09-20 12:02:26 -07005125 }
Robert Carr866455f2019-04-02 16:28:26 -07005126
5127 sp<Layer> p = layer;
5128 while (p != nullptr) {
5129 if (excludeLayers.count(p) != 0) {
5130 return;
5131 }
5132 p = p->getParent();
5133 }
5134
chaviwa76b2712017-09-20 12:02:26 -07005135 visitor(layer);
5136 });
5137 };
Robert Carr108b2c72019-04-02 16:32:58 -07005138
5139 bool outCapturedSecureLayers = false;
5140 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5141 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005142}
5143
5144status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5145 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005146 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005147 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005148 bool useIdentityTransform,
5149 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005150 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005151
Peiyong Lin0e003c92018-09-17 11:09:51 -07005152 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005153 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5154 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005155 *outBuffer =
5156 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5157 static_cast<android_pixel_format>(reqPixelFormat), 1,
5158 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005159
Robert Carr108b2c72019-04-02 16:32:58 -07005160 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5161 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005162}
5163
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005164status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5165 TraverseLayersFunction traverseLayers,
5166 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005167 bool useIdentityTransform,
5168 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005169 // This mutex protects syncFd and captureResult for communication of the return values from the
5170 // main thread back to this Binder thread
5171 std::mutex captureMutex;
5172 std::condition_variable captureCondition;
5173 std::unique_lock<std::mutex> captureLock(captureMutex);
5174 int syncFd = -1;
5175 std::optional<status_t> captureResult;
5176
Robert Carr03480e22018-01-04 16:02:06 -08005177 const int uid = IPCThreadState::self()->getCallingUid();
5178 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5179
Dominik Laskowski8c001672018-05-30 16:52:06 -07005180 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005181 // If there is a refresh pending, bug out early and tell the binder thread to try again
5182 // after the refresh.
5183 if (mRefreshPending) {
5184 ATRACE_NAME("Skipping screenshot for now");
5185 std::unique_lock<std::mutex> captureLock(captureMutex);
5186 captureResult = std::make_optional<status_t>(EAGAIN);
5187 captureCondition.notify_one();
5188 return;
5189 }
5190
5191 status_t result = NO_ERROR;
5192 int fd = -1;
5193 {
5194 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005195 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005196 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005197 useIdentityTransform, forSystem, &fd,
5198 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005199 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005200 }
5201
5202 {
5203 std::unique_lock<std::mutex> captureLock(captureMutex);
5204 syncFd = fd;
5205 captureResult = std::make_optional<status_t>(result);
5206 captureCondition.notify_one();
5207 }
5208 });
5209
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005210 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005211 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005212 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005213 while (*captureResult == EAGAIN) {
5214 captureResult.reset();
5215 result = postMessageAsync(message);
5216 if (result != NO_ERROR) {
5217 return result;
5218 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005219 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005220 }
5221 result = *captureResult;
5222 }
5223
5224 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005225 sync_wait(syncFd, -1);
5226 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005227 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005228
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005229 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005230}
5231
chaviwa76b2712017-09-20 12:02:26 -07005232void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005233 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005234 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5235 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005236 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005237
chaviwa76b2712017-09-20 12:02:26 -07005238 const auto reqWidth = renderArea.getReqWidth();
5239 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005240 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005241 const auto transform = renderArea.getTransform();
5242 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005243
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005244 renderengine::DisplaySettings clientCompositionDisplay;
5245 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005246
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005247 // assume that bounds are never offset, and that they are the same as the
5248 // buffer bounds.
5249 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005250 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005251 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005252
5253 // Now take into account the rotation flag. We append a transform that
5254 // rotates the layer stack about the origin, then translate by buffer
5255 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005256 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005257 int displacementX = 0;
5258 int displacementY = 0;
5259 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5260 switch (rotation) {
5261 case ui::Transform::ROT_90:
5262 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005263 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005264 break;
5265 case ui::Transform::ROT_180:
5266 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005267 displacementY = renderArea.getBounds().getWidth();
5268 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005269 break;
5270 case ui::Transform::ROT_270:
5271 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005272 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005273 break;
5274 default:
5275 break;
5276 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005277
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005278 // We need to transform the clipping window into the right spot.
5279 // First, rotate the clipping rectangle by the rotation hint to get the
5280 // right orientation
5281 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5282 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5283 const vec4 rotClipTL = rotMatrix * clipTL;
5284 const vec4 rotClipBR = rotMatrix * clipBR;
5285 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5286 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5287 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5288 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5289
5290 // Now reposition the clipping rectangle with the displacement vector
5291 // computed above.
5292 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005293 clientCompositionDisplay.clip =
5294 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5295 newClipRight + displacementX, newClipBottom + displacementY);
5296
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005297 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005298 clientCompositionDisplay.globalTransform =
5299 clipTransform * clientCompositionDisplay.globalTransform;
5300
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005301 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5302 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005303
chaviw50da5042018-04-09 13:49:37 -07005304 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005305
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005306 renderengine::LayerSettings fillLayer;
5307 fillLayer.source.buffer.buffer = nullptr;
5308 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5309 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5310 fillLayer.alpha = half(alpha);
5311 clientCompositionLayers.push_back(fillLayer);
5312
5313 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005314 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005315 const bool supportProtectedContent = false;
5316 Region clip(renderArea.getBounds());
5317 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5318 clip,
5319 useIdentityTransform,
5320 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5321 renderArea.isSecure(),
5322 supportProtectedContent,
5323 clearRegion,
5324 };
5325 auto result = layer->prepareClientComposition(targetSettings);
5326 if (result) {
5327 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005328 }
chaviwa76b2712017-09-20 12:02:26 -07005329 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005330
5331 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005332 // Use an empty fence for the buffer fence, since we just created the buffer so
5333 // there is no need for synchronization with the GPU.
5334 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005335 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005336 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005337 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005338 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005339
5340 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005341}
5342
chaviwa76b2712017-09-20 12:02:26 -07005343status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5344 TraverseLayersFunction traverseLayers,
5345 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005346 bool useIdentityTransform, bool forSystem,
5347 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005348 ATRACE_CALL();
5349
chaviwa76b2712017-09-20 12:02:26 -07005350 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005351 outCapturedSecureLayers =
5352 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005353 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005354
Robert Carr03480e22018-01-04 16:02:06 -08005355 // We allow the system server to take screenshots of secure layers for
5356 // use in situations like the Screen-rotation animation and place
5357 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005358 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005359 ALOGW("FB is protected: PERMISSION_DENIED");
5360 return PERMISSION_DENIED;
5361 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005362 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005363 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005364}
5365
chaviw95ef3c42019-02-14 10:55:09 -08005366void SurfaceFlinger::setInputWindowsFinished() {
5367 Mutex::Autolock _l(mStateLock);
5368
5369 mPendingSyncInputWindows = false;
5370 mTransactionCV.broadcast();
5371}
chaviw5f21a5e2019-02-14 10:00:34 -08005372
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005373// ---------------------------------------------------------------------------
5374
Dan Stoza412903f2017-04-27 13:42:17 -07005375void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5376 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005377}
5378
Dan Stoza412903f2017-04-27 13:42:17 -07005379void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5380 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005381}
5382
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005383void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005384 const LayerVector::Visitor& visitor) {
5385 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005386 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005387 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005388 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005389 continue;
5390 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005391 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005392 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005393 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005394 return;
5395 }
chaviwa76b2712017-09-20 12:02:26 -07005396 if (!layer->isVisible()) {
5397 return;
5398 }
5399 visitor(layer);
5400 });
5401 }
5402}
5403
Dominik Laskowski22488f62019-03-28 09:53:04 -07005404void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5405 const std::vector<int32_t>& allowedConfigs) {
5406 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005407 return;
5408 }
5409
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005410 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5411 allowedConfigs.end());
5412 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5413 return;
5414 }
5415
Ady Abraham838de062019-02-04 10:24:03 -08005416 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005417 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5418
5419 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5420 // that listeners that care about a change in allowed configs can get the notification.
5421 // Giving current ActiveConfig so that most other listeners would just drop the event
5422 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5423 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005424
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005425 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5426 const auto& type = mScheduler->getPreferredRefreshRateType();
5427 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5428 if (isDisplayConfigAllowed(config.configId)) {
5429 ALOGV("switching to Scheduler preferred config %d", config.configId);
5430 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5431 } else {
5432 // Set the highest allowed config by iterating backwards on available refresh rates
5433 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5434 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5435 if (isDisplayConfigAllowed(iter->second.configId)) {
5436 ALOGV("switching to allowed config %d", iter->second.configId);
5437 setDesiredActiveConfig(
5438 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5439 break;
5440 }
5441 }
5442 }
5443 } else if (!allowedConfigs.empty()) {
5444 ALOGV("switching to config %d", allowedConfigs[0]);
5445 setDesiredActiveConfig(
5446 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5447 }
Ady Abraham838de062019-02-04 10:24:03 -08005448}
5449
Dominik Laskowski22488f62019-03-28 09:53:04 -07005450status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005451 const std::vector<int32_t>& allowedConfigs) {
5452 ATRACE_CALL();
5453
Dominik Laskowski22488f62019-03-28 09:53:04 -07005454 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005455 return BAD_VALUE;
5456 }
5457
Ady Abraham34392f72019-04-10 11:29:27 -07005458 if (mDebugDisplayConfigSetByBackdoor) {
5459 // ignore this request as config is overridden by backdoor
5460 return NO_ERROR;
5461 }
5462
Ady Abrahama3129fb2019-10-18 14:17:23 -07005463 postMessageSync(new LambdaMessage([&]() {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005464 const auto display = getDisplayDeviceLocked(displayToken);
5465 if (!display) {
5466 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5467 displayToken.get());
5468 } else if (display->isVirtual()) {
5469 ALOGW("Attempt to set allowed display configs for virtual display");
5470 } else {
Ady Abrahama3129fb2019-10-18 14:17:23 -07005471 Mutex::Autolock lock(mStateLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005472 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5473 }
Ady Abraham838de062019-02-04 10:24:03 -08005474 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005475
Ady Abraham838de062019-02-04 10:24:03 -08005476 return NO_ERROR;
5477}
5478
Dominik Laskowski22488f62019-03-28 09:53:04 -07005479status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005480 std::vector<int32_t>* outAllowedConfigs) {
5481 ATRACE_CALL();
5482
Dominik Laskowski22488f62019-03-28 09:53:04 -07005483 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005484 return BAD_VALUE;
5485 }
5486
Dominik Laskowski22488f62019-03-28 09:53:04 -07005487 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005488
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005489 const auto display = getDisplayDeviceLocked(displayToken);
5490 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005491 return NAME_NOT_FOUND;
5492 }
5493
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005494 if (display->isPrimary()) {
5495 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5496 }
5497
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005498 return NO_ERROR;
5499}
5500
Ana Krulec0782b882019-10-15 17:34:54 -07005501status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
5502 int32_t defaultModeId, float minRefreshRate,
5503 float maxRefreshRate) {
5504 ATRACE_CALL();
5505
5506 if (!displayToken) {
5507 return BAD_VALUE;
5508 }
5509
Ana Krulec234bb162019-11-10 22:55:55 +01005510 postMessageSync(new LambdaMessage([&]() {
5511 const auto display = getDisplayDeviceLocked(displayToken);
5512 if (!display) {
5513 ALOGE("Attempt to set desired display configs for invalid display token %p",
5514 displayToken.get());
5515 } else if (display->isVirtual()) {
5516 ALOGW("Attempt to set desired display configs for virtual display");
5517 } else {
5518 // TODO(b/142507213): Plug through to HWC once the interface is ready.
5519 Mutex::Autolock lock(mStateLock);
5520 const DesiredDisplayConfigSpecs desiredDisplayConfigSpecs = {defaultModeId,
5521 minRefreshRate,
5522 maxRefreshRate};
5523 if (desiredDisplayConfigSpecs == mDesiredDisplayConfigSpecs) {
5524 return;
5525 }
5526 ALOGV("Updating desired display configs");
5527 ALOGD("desiredDisplayConfigSpecs: defaultId: %d min: %.f max: %.f decisions: ",
5528 desiredDisplayConfigSpecs.defaultModeId, desiredDisplayConfigSpecs.minRefreshRate,
5529 desiredDisplayConfigSpecs.maxRefreshRate);
5530 mDesiredDisplayConfigSpecs = desiredDisplayConfigSpecs;
5531 }
5532 }));
5533 return NO_ERROR;
5534}
5535
5536status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
5537 int32_t* outDefaultModeId,
5538 float* outMinRefreshRate,
5539 float* outMaxRefreshRate) {
5540 ATRACE_CALL();
5541
5542 if (!displayToken || !outDefaultModeId || !outMinRefreshRate || !outMaxRefreshRate) {
5543 return BAD_VALUE;
5544 }
5545
5546 Mutex::Autolock lock(mStateLock);
5547 const auto display = getDisplayDeviceLocked(displayToken);
5548 if (!display) {
5549 return NAME_NOT_FOUND;
5550 }
5551
5552 if (display->isPrimary()) {
5553 *outDefaultModeId = mDesiredDisplayConfigSpecs.defaultModeId;
5554 *outMinRefreshRate = mDesiredDisplayConfigSpecs.minRefreshRate;
5555 *outMaxRefreshRate = mDesiredDisplayConfigSpecs.maxRefreshRate;
5556 }
Ana Krulec0782b882019-10-15 17:34:54 -07005557
5558 return NO_ERROR;
5559}
5560
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005561void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005562 mFlinger->setInputWindowsFinished();
5563}
5564
Robert Carrc0df3122019-04-11 13:18:21 -07005565sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5566 BBinder *b = handle->localBinder();
5567 if (b == nullptr) {
5568 return nullptr;
5569 }
5570 auto it = mLayersByLocalBinderToken.find(b);
5571 if (it != mLayersByLocalBinderToken.end()) {
5572 return it->second.promote();
5573 }
5574 return nullptr;
5575}
5576
Dominik Laskowski75848362019-11-11 17:57:20 -08005577void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005578 mNumLayers++;
5579 mScheduler->registerLayer(layer);
5580}
5581
5582void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5583 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005584 removeFromOffscreenLayers(layer);
5585}
5586
5587// WARNING: ONLY CALL THIS FROM LAYER DTOR
5588// Here we add children in the current state to offscreen layers and remove the
5589// layer itself from the offscreen layer list. Since
5590// this is the dtor, it is safe to access the current state. This keeps us
5591// from dangling children layers such that they are not reachable from the
5592// Drawing state nor the offscreen layer list
5593// See b/141111965
5594void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5595 for (auto& child : layer->getCurrentChildren()) {
5596 mOffscreenLayers.emplace(child.get());
5597 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005598 mOffscreenLayers.erase(layer);
5599}
5600
Alec Mouri4545a8a2019-08-08 20:05:32 -07005601void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5602 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5603}
5604
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005605status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5606 float lightPosY, float lightPosZ,
5607 float lightRadius) {
5608 Mutex::Autolock _l(mStateLock);
5609 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5610 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5611 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5612 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5613 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5614
5615 // these values are overridden when calculating the shadow settings for a layer.
5616 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5617 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005618 return NO_ERROR;
5619}
5620
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005621} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005622
Mathias Agopian3f844832013-08-07 21:24:32 -07005623#if defined(__gl_h_)
5624#error "don't include gl/gl.h in this file"
5625#endif
5626
5627#if defined(__gl2_h_)
5628#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005629#endif