blob: 3403b280f0441c80055012b13024684cdf8a7fde [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
Ady Abraham2139f732019-11-13 18:56:40 -0800545 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
546 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800547 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800548 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549}
550
Dan Stoza436ccf32018-06-21 12:10:12 -0700551uint32_t SurfaceFlinger::getNewTexture() {
552 {
553 std::lock_guard lock(mTexturePoolMutex);
554 if (!mTexturePool.empty()) {
555 uint32_t name = mTexturePool.back();
556 mTexturePool.pop_back();
557 ATRACE_INT("TexturePoolSize", mTexturePool.size());
558 return name;
559 }
560
561 // The pool was too small, so increase it for the future
562 ++mTexturePoolSize;
563 }
564
565 // The pool was empty, so we need to get a new texture name directly using a
566 // blocking call to the main thread
567 uint32_t name = 0;
568 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
569 return name;
570}
571
Mathias Agopian3f844832013-08-07 21:24:32 -0700572void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700573 std::lock_guard lock(mTexturePoolMutex);
574 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
575 // to actually delete this or not based on mTexturePoolSize
576 mTexturePool.push_back(texture);
577 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700578}
579
Wei Wangf9b05ee2017-07-19 20:59:39 -0700580// Do not call property_set on main thread which will be blocked by init
581// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700582void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700583 ALOGI( "SurfaceFlinger's main thread ready to run. "
584 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700585 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900586
Steven Thomasb02664d2017-07-26 18:48:28 -0700587 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800588
Steven Thomasb02664d2017-07-26 18:48:28 -0700589 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700590 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800591 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700592 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
593 renderengine::RenderEngineCreationArgs::Builder()
594 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
595 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
596 .setUseColorManagerment(useColorManagement)
597 .setEnableProtectedContext(enable_protected_contents(false))
598 .setPrecacheToneMapperShaderOnly(false)
599 .setContextPriority(useContextPriority
600 ? renderengine::RenderEngine::ContextPriority::HIGH
601 : renderengine::RenderEngine::ContextPriority::MEDIUM)
602 .build()));
Steven Thomasb02664d2017-07-26 18:48:28 -0700603
604 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
605 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700606 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
607 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800608 // Process any initial hotplug and resulting display changes.
609 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700610 const auto display = getDefaultDisplayDeviceLocked();
611 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700612 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700613 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800614
Steven Thomas050b2c82017-03-06 11:45:16 -0800615 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700616 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700617 // This callback is called from the vr flinger dispatch thread. We
618 // need to call signalTransaction(), which requires holding
619 // mStateLock when we're not on the main thread. Acquiring
620 // mStateLock from the vr flinger dispatch thread might trigger a
621 // deadlock in surface flinger (see b/66916578), so post a message
622 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700623 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700624 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
625 mVrFlingerRequestsDisplay = requestDisplay;
626 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700627 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800628 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700629 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
630 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700631 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700632 .value_or(0),
633 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 if (!mVrFlinger) {
635 ALOGE("Failed to start vrflinger");
636 }
637 }
638
Mathias Agopian92a979a2012-08-02 18:32:23 -0700639 // initialize our drawing state
640 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700641
Andy McFadden13a082e2012-08-24 10:16:42 -0700642 // set initial conditions (e.g. unblank default device)
643 initializeDisplays();
644
Steven Thomas137d4bc2019-07-25 16:55:14 -0700645 char primeShaderCache[PROPERTY_VALUE_MAX];
646 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
647 if (atoi(primeShaderCache)) {
648 getRenderEngine().primeCache();
649 }
Dan Stoza4e637772016-07-28 13:31:51 -0700650
Wei Wangf9b05ee2017-07-19 20:59:39 -0700651 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700652
653 const bool presentFenceReliable =
654 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
655 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700656
657 if (mStartPropertySetThread->Start() != NO_ERROR) {
658 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800660
Dan Stoza9e56aa02015-11-02 13:00:03 -0800661 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700662}
663
Romain Guy11d63f42017-07-20 12:47:14 -0700664void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700665 Mutex::Autolock _l(mStateLock);
666
Romain Guy11d63f42017-07-20 12:47:14 -0700667 char value[PROPERTY_VALUE_MAX];
668
669 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800670 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700671 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800672 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100673
674 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700675 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800676
677 property_get("persist.sys.sf.color_mode", value, "0");
678 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700679}
680
Mathias Agopiana67e4182012-06-19 17:26:12 -0700681void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800682 // Start boot animation service by setting a property mailbox
683 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800685 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700686 if (mStartPropertySetThread->join() != NO_ERROR) {
687 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800688 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700689}
690
Mathias Agopian875d8e12013-06-07 15:35:48 -0700691size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700692 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700693}
694
Mathias Agopian875d8e12013-06-07 15:35:48 -0700695size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700696 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700697}
698
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800699// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800700
Jamie Gennis582270d2011-08-17 18:19:00 -0700701bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800702 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800703 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800704 return authenticateSurfaceTextureLocked(bufferProducer);
705}
706
707bool SurfaceFlinger::authenticateSurfaceTextureLocked(
708 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800709 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800710 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800711}
712
Brian Anderson6b376712017-04-04 10:51:39 -0700713status_t SurfaceFlinger::getSupportedFrameTimestamps(
714 std::vector<FrameEvent>* outSupported) const {
715 *outSupported = {
716 FrameEvent::REQUESTED_PRESENT,
717 FrameEvent::ACQUIRE,
718 FrameEvent::LATCH,
719 FrameEvent::FIRST_REFRESH_START,
720 FrameEvent::LAST_REFRESH_START,
721 FrameEvent::GPU_COMPOSITION_DONE,
722 FrameEvent::DEQUEUE_READY,
723 FrameEvent::RELEASE,
724 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700725 ConditionalLock _l(mStateLock,
726 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700727 if (!getHwComposer().hasCapability(
728 HWC2::Capability::PresentFenceIsNotReliable)) {
729 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
730 }
731 return NO_ERROR;
732}
733
Dominik Laskowski22488f62019-03-28 09:53:04 -0700734status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
735 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700736 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700737 return BAD_VALUE;
738 }
739
Dominik Laskowski22488f62019-03-28 09:53:04 -0700740 Mutex::Autolock lock(mStateLock);
741
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800742 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700743 if (!displayId) {
744 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700745 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700746
Mathias Agopian8b736f12012-08-13 17:54:26 -0700747 // TODO: Not sure if display density should handled by SF any longer
748 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700749 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700750 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700751 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800752 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700753 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754 }
755 return density;
756 }
757 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700758 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700760 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761 return getDensityFromProperty("ro.sf.lcd_density"); }
762 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700763
Dan Stoza7f7da322014-05-02 15:26:25 -0700764 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700765
Dominik Laskowski075d3172018-05-24 15:50:06 -0700766 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700767 DisplayInfo info = DisplayInfo();
768
Dan Stoza9e56aa02015-11-02 13:00:03 -0800769 float xdpi = hwConfig->getDpiX();
770 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700771
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700772 info.w = hwConfig->getWidth();
773 info.h = hwConfig->getHeight();
774 // Default display viewport to display width and height
775 info.viewportW = info.w;
776 info.viewportH = info.h;
777
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800778 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 // The density of the device is provided by a build property
780 float density = Density::getBuildDensity() / 160.0f;
781 if (density == 0) {
782 // the build doesn't provide a density -- this is wrong!
783 // use xdpi instead
784 ALOGE("ro.sf.lcd_density must be defined as a build property");
785 density = xdpi / 160.0f;
786 }
787 if (Density::getEmuDensity()) {
788 // if "qemu.sf.lcd_density" is specified, it overrides everything
789 xdpi = ydpi = density = Density::getEmuDensity();
790 density /= 160.0f;
791 }
792 info.density = density;
793
794 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700795 const auto display = getDefaultDisplayDeviceLocked();
796 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700797
798 // This is for screenrecord
799 const Rect viewport = display->getViewport();
800 if (viewport.isValid()) {
801 info.viewportW = uint32_t(viewport.getWidth());
802 info.viewportH = uint32_t(viewport.getHeight());
803 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700804 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 } else {
806 // TODO: where should this value come from?
807 static const int TV_DENSITY = 213;
808 info.density = TV_DENSITY / 160.0f;
809 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700810
811 const auto display = getDisplayDeviceLocked(displayToken);
812 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 }
814
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 info.xdpi = xdpi;
816 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800817 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800818
819 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700820 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800821
Andy McFadden91b2ca82014-06-13 14:04:23 -0700822 // This is how far in advance a buffer must be queued for
823 // presentation at a given time. If you want a buffer to appear
824 // on the screen at time N, you must submit the buffer before
825 // (N - presentationDeadline).
826 //
827 // Normally it's one full refresh period (to give SF a chance to
828 // latch the buffer), but this can be reduced by configuring a
829 // DispSync offset. Any additional delays introduced by the hardware
830 // composer or panel must be accounted for here.
831 //
832 // We add an additional 1ms to allow for processing time and
833 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700834 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700835
836 // All non-virtual displays are currently considered secure.
837 info.secure = true;
838
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800839 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700840 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800841 std::swap(info.w, info.h);
842 }
843
Michael Wright28f24d02016-07-12 13:30:53 -0700844 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700845 }
846
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 return NO_ERROR;
848}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700849
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700850status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
851 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700852 return BAD_VALUE;
853 }
854
Ana Krulecc2870422019-01-29 19:00:58 -0800855 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700856 return NO_ERROR;
857}
858
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700859int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
860 const auto display = getDisplayDevice(displayToken);
861 if (!display) {
862 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800863 return BAD_VALUE;
864 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700865
Steven Thomasc9098452019-09-30 17:15:05 -0700866 if (display->isPrimary()) {
867 std::lock_guard<std::mutex> lock(mActiveConfigLock);
868 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800869 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700870 }
Steven Thomasc9098452019-09-30 17:15:05 -0700871 }
Ady Abraham2139f732019-11-13 18:56:40 -0800872
873 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700874}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700875
Ady Abraham03b02dd2019-03-21 15:40:11 -0700876void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800877 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800878 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
879 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800880
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800881 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800882 // config twice. However event generation config might have changed so we need to update it
883 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800884 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700885 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
886 mDesiredActiveConfig = info;
887 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800888
889 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800890 // This will trigger HWC refresh without resetting the idle timer.
891 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700892 // Start receiving vsync samples now, so that we can detect a period
893 // switch.
894 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700895 // As we called to set period, we will call to onRefreshRateChangeCompleted once
896 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700897 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800898
899 mPhaseOffsets->setRefreshRateFps(refreshRate.fps);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700900 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800901 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800902 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700903
904 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800905 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700906 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800907}
908
909status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
910 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800911
912 std::vector<int32_t> allowedConfig;
913 allowedConfig.push_back(mode);
914
915 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800916}
917
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800918void SurfaceFlinger::setActiveConfigInternal() {
919 ATRACE_CALL();
920
Dominik Laskowski22488f62019-03-28 09:53:04 -0700921 const auto display = getDefaultDisplayDeviceLocked();
922 if (!display) {
923 return;
924 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800925
Dominik Laskowski22488f62019-03-28 09:53:04 -0700926 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800927 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700928 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929 display->setActiveConfig(mUpcomingActiveConfig.configId);
930
Ady Abraham2139f732019-11-13 18:56:40 -0800931 auto refreshRate =
932 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
933 mPhaseOffsets->setRefreshRateFps(refreshRate.fps);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700934 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800935 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700936
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800937 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800938 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
939 mUpcomingActiveConfig.configId);
940 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800941}
942
Ady Abraham53852a52019-05-28 18:07:44 -0700943void SurfaceFlinger::desiredActiveConfigChangeDone() {
944 std::lock_guard<std::mutex> lock(mActiveConfigLock);
945 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
946 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700947
948 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800949 auto refreshRate =
950 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
951 mPhaseOffsets->setRefreshRateFps(refreshRate.fps);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700952 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700953}
954
Dominik Laskowski22488f62019-03-28 09:53:04 -0700955bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800956 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800957 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800958 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700959 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800960 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700961 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 return true;
963 }
964
965 // We received the present fence from the HWC, so we assume it successfully updated
966 // the config, hence we update SF.
967 mCheckPendingFence = false;
968 setActiveConfigInternal();
969 }
970
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800971 // Store the local variable to release the lock.
972 ActiveConfigInfo desiredActiveConfig;
973 {
974 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800975 if (!mDesiredActiveConfigChanged) {
976 return false;
977 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 desiredActiveConfig = mDesiredActiveConfig;
979 }
980
Ady Abraham2139f732019-11-13 18:56:40 -0800981 auto refreshRate =
982 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
983 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
984 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -0700985 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800986 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
987 // display is not valid or we are already in the requested mode
988 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700989 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800990 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800992
Ady Abraham838de062019-02-04 10:24:03 -0800993 // Desired active config was set, it is different than the config currently in use, however
994 // allowed configs might have change by the time we process the refresh.
995 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -0700996 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -0700997 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -0800998 return false;
999 }
Alec Mouri7f015182019-07-11 13:56:22 -07001000
Ady Abrahamb838aed2019-02-12 15:30:16 -08001001 mUpcomingActiveConfig = desiredActiveConfig;
1002 const auto displayId = display->getId();
1003 LOG_ALWAYS_FATAL_IF(!displayId);
1004
Ady Abraham2139f732019-11-13 18:56:40 -08001005 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001007 // TODO(b/142753666) use constrains
1008 HWC2::VsyncPeriodChangeConstraints constraints;
1009 constraints.desiredTimeNanos = systemTime();
1010 constraints.seamlessRequired = false;
1011
1012 HWC2::VsyncPeriodChangeTimeline outTimeline;
1013 auto status =
1014 getHwComposer().setActiveConfigWithConstraints(*displayId,
1015 mUpcomingActiveConfig.configId.value(),
1016 constraints, &outTimeline);
1017 if (status != NO_ERROR) {
1018 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1019 return false;
1020 }
1021
1022 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1023 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001024 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001025 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001026}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001027
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001028status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1029 Vector<ColorMode>* outColorModes) {
1030 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001031 return BAD_VALUE;
1032 }
1033
Peiyong Lina52f0292018-03-14 17:26:31 -07001034 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001035 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001036 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001037 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1038
1039 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1040 if (!displayId) {
1041 return NAME_NOT_FOUND;
1042 }
1043
Dominik Laskowski075d3172018-05-24 15:50:06 -07001044 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001045 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001046 }
Michael Wright28f24d02016-07-12 13:30:53 -07001047 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001048
1049 // If it's built-in display and the configuration claims it's not wide color capable,
1050 // filter out all wide color modes. The typical reason why this happens is that the
1051 // hardware is not good enough to support GPU composition of wide color, and thus the
1052 // OEMs choose to disable this capability.
1053 if (isInternalDisplay && !hasWideColorDisplay) {
1054 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1055 isWideColorMode);
1056 } else {
1057 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1058 }
Michael Wright28f24d02016-07-12 13:30:53 -07001059
1060 return NO_ERROR;
1061}
1062
Daniel Solomon42d04562019-01-20 21:03:19 -08001063status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1064 ui::DisplayPrimaries &primaries) {
1065 if (!displayToken) {
1066 return BAD_VALUE;
1067 }
1068
1069 // Currently we only support this API for a single internal display.
1070 if (getInternalDisplayToken() != displayToken) {
1071 return BAD_VALUE;
1072 }
1073
1074 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1075 return NO_ERROR;
1076}
1077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1079 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001080 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001081 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001082 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001086 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001087 Vector<ColorMode> modes;
1088 getDisplayColorModes(displayToken, &modes);
1089 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1090 if (mode < ColorMode::NATIVE || !exists) {
1091 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1092 decodeColorMode(mode).c_str(), mode, displayToken.get());
1093 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001094 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const auto display = getDisplayDevice(displayToken);
1096 if (!display) {
1097 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1098 decodeColorMode(mode).c_str(), mode, displayToken.get());
1099 } else if (display->isVirtual()) {
1100 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1101 decodeColorMode(mode).c_str(), mode);
1102 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001103 display->getCompositionDisplay()->setColorProfile(
1104 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1105 RenderIntent::COLORIMETRIC,
1106 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001107 }
1108 }));
1109
Michael Wright28f24d02016-07-12 13:30:53 -07001110 return NO_ERROR;
1111}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001112
Svetoslavd85084b2014-03-20 10:28:31 -07001113status_t SurfaceFlinger::clearAnimationFrameStats() {
1114 Mutex::Autolock _l(mStateLock);
1115 mAnimFrameTracker.clearStats();
1116 return NO_ERROR;
1117}
1118
1119status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1120 Mutex::Autolock _l(mStateLock);
1121 mAnimFrameTracker.getStats(outStats);
1122 return NO_ERROR;
1123}
1124
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001125status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1126 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001127 Mutex::Autolock _l(mStateLock);
1128
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129 const auto display = getDisplayDeviceLocked(displayToken);
1130 if (!display) {
1131 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001132 return BAD_VALUE;
1133 }
1134
Peiyong Linfb069302018-04-25 14:34:31 -07001135 // At this point the DisplayDeivce should already be set up,
1136 // meaning the luminance information is already queried from
1137 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001138 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001139 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1140 capabilities.getDesiredMaxLuminance(),
1141 capabilities.getDesiredMaxAverageLuminance(),
1142 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001143
1144 return NO_ERROR;
1145}
1146
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001147status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1148 ui::PixelFormat* outFormat,
1149 ui::Dataspace* outDataspace,
1150 uint8_t* outComponentMask) const {
1151 if (!outFormat || !outDataspace || !outComponentMask) {
1152 return BAD_VALUE;
1153 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001154 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001155 if (!display || !display->getId()) {
1156 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1157 return BAD_VALUE;
1158 }
1159 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1160 outDataspace, outComponentMask);
1161}
1162
Kevin DuBois74e53772018-11-19 10:52:38 -08001163status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1164 bool enable, uint8_t componentMask,
1165 uint64_t maxFrames) const {
1166 const auto display = getDisplayDevice(displayToken);
1167 if (!display || !display->getId()) {
1168 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1169 return BAD_VALUE;
1170 }
1171
1172 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1173 componentMask, maxFrames);
1174}
1175
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001176status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1177 uint64_t maxFrames, uint64_t timestamp,
1178 DisplayedFrameStats* outStats) const {
1179 const auto display = getDisplayDevice(displayToken);
1180 if (!display || !display->getId()) {
1181 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1182 return BAD_VALUE;
1183 }
1184
1185 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1186 outStats);
1187}
1188
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001189status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1190 if (!outSupported) {
1191 return BAD_VALUE;
1192 }
1193 *outSupported = getRenderEngine().supportsProtectedContent();
1194 return NO_ERROR;
1195}
1196
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001197status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1198 bool* outIsWideColorDisplay) const {
1199 if (!displayToken || !outIsWideColorDisplay) {
1200 return BAD_VALUE;
1201 }
1202 Mutex::Autolock _l(mStateLock);
1203 const auto display = getDisplayDeviceLocked(displayToken);
1204 if (!display) {
1205 return BAD_VALUE;
1206 }
Peiyong Linff84a152019-05-17 18:36:19 -07001207
1208 // Use hasWideColorDisplay to override built-in display.
1209 const auto displayId = display->getId();
1210 if (displayId && displayId == getInternalDisplayIdLocked()) {
1211 *outIsWideColorDisplay = hasWideColorDisplay;
1212 return NO_ERROR;
1213 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001214 *outIsWideColorDisplay = display->hasWideColorGamut();
1215 return NO_ERROR;
1216}
1217
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001219 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001220 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001221
Dominik Laskowski6505f792019-09-18 11:10:05 -07001222 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1223 mEventQueue->setEventConnection(
1224 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001225 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001226 }));
1227
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001228 return NO_ERROR;
1229}
1230
1231status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001232 Mutex::Autolock lock(mStateLock);
1233 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001234}
1235
Lloyd Pique755e3192018-01-31 16:46:15 -08001236status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1237 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001238 // Try to acquire a lock for 1s, fail gracefully
1239 const status_t err = mStateLock.timedLock(s2ns(1));
1240 const bool locked = (err == NO_ERROR);
1241 if (!locked) {
1242 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1243 return TIMED_OUT;
1244 }
1245
1246 outLayers->clear();
1247 mCurrentState.traverseInZOrder([&](Layer* layer) {
1248 outLayers->push_back(layer->getLayerDebugInfo());
1249 });
1250
1251 mStateLock.unlock();
1252 return NO_ERROR;
1253}
1254
Peiyong Linc6780972018-10-28 15:24:08 -07001255status_t SurfaceFlinger::getCompositionPreference(
1256 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1257 Dataspace* outWideColorGamutDataspace,
1258 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001259 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001260 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001261 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001262 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001263 return NO_ERROR;
1264}
1265
Dan Stozaec460082018-12-17 15:35:09 -08001266status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1267 const sp<IBinder>& stopLayerHandle,
1268 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001269 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001270 return BAD_VALUE;
1271 }
1272 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001273 return NO_ERROR;
1274}
1275
Dan Stozaec460082018-12-17 15:35:09 -08001276status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001277 if (!listener) {
1278 return BAD_VALUE;
1279 }
Dan Stozaec460082018-12-17 15:35:09 -08001280 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001281 return NO_ERROR;
1282}
Dan Gittik57e63c52019-01-18 16:37:54 +00001283
1284status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1285 bool* outSupport) const {
1286 if (!displayToken || !outSupport) {
1287 return BAD_VALUE;
1288 }
1289 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1290 if (!displayId) {
1291 return NAME_NOT_FOUND;
1292 }
1293 *outSupport =
1294 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1295 return NO_ERROR;
1296}
1297
1298status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1299 float brightness) const {
1300 if (!displayToken) {
1301 return BAD_VALUE;
1302 }
1303 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1304 if (!displayId) {
1305 return NAME_NOT_FOUND;
1306 }
1307 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1308}
1309
Ady Abraham8532d012019-05-08 14:50:56 -07001310status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1311 PowerHint powerHint = static_cast<PowerHint>(hintId);
1312
1313 if (powerHint == PowerHint::INTERACTION) {
1314 mScheduler->notifyTouchEvent();
1315 }
1316
1317 return NO_ERROR;
1318}
1319
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001320// ----------------------------------------------------------------------------
1321
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001322sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001323 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001324 const auto& handle =
1325 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001326
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001327 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001328}
1329
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001330// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001331
1332void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001333 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001334}
1335
1336void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001337 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001338 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001339}
1340
1341void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001342 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001343 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001344}
1345
1346void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001347 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001348 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349}
1350
1351status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001352 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001353 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001354}
1355
1356status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001357 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001358 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001359 if (res == NO_ERROR) {
1360 msg->wait();
1361 }
1362 return res;
1363}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001364
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001365void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001366 do {
1367 waitForEvent();
1368 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001369}
1370
Dominik Laskowski83b88212018-12-11 13:34:06 -08001371nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001372 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001373 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1374 return 0;
1375 }
1376
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001377 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001378}
1379
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001380void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001381 int64_t timestamp,
1382 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001383 ATRACE_NAME("SF onVsync");
1384
Ady Abraham7159f572019-10-11 11:10:18 -07001385 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1386
Steven Thomas3cfac282017-02-06 12:29:30 -08001387 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001388 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001389 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001390 return;
1391 }
1392
Dominik Laskowski075d3172018-05-24 15:50:06 -07001393 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001394 return;
1395 }
1396
Dominik Laskowski075d3172018-05-24 15:50:06 -07001397 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001398 // For now, we don't do anything with external display vsyncs.
1399 return;
1400 }
1401
Alec Mourif8e689c2019-05-20 18:32:22 -07001402 bool periodFlushed = false;
1403 mScheduler->addResyncSample(timestamp, &periodFlushed);
1404 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001405 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001406 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001407}
1408
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001409void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001410 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1411 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001412}
1413
Ady Abraham2139f732019-11-13 18:56:40 -08001414bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001415 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001416}
1417
Ady Abraham2139f732019-11-13 18:56:40 -08001418void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1419 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001420 const auto display = getDefaultDisplayDeviceLocked();
1421 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001422 return;
1423 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001424 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001425
Ana Krulec7d1d6832018-12-27 11:10:09 -08001426 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001427 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1428 ALOGV("Skipping config %d as it is not part of allowed configs",
1429 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001430 return;
1431 }
1432
Ady Abraham2139f732019-11-13 18:56:40 -08001433 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001434}
1435
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001436void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001437 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001438 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001439 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001440
Lloyd Piqueba04e622017-12-14 17:11:26 -08001441 // Ignore events that do not have the right sequenceId.
1442 if (sequenceId != getBE().mComposerSequenceId) {
1443 return;
1444 }
1445
Steven Thomasb02664d2017-07-26 18:48:28 -07001446 // Only lock if we're not on the main thread. This function is normally
1447 // called on a hwbinder thread, but for the primary display it's called on
1448 // the main thread with the state lock already held, so don't attempt to
1449 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001450 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001451
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001452 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001453
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001454 if (std::this_thread::get_id() == mMainThreadId) {
1455 // Process all pending hot plug events immediately if we are on the main thread.
1456 processDisplayHotplugEventsLocked();
1457 }
1458
Lloyd Piqueba04e622017-12-14 17:11:26 -08001459 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001460}
1461
Ady Abraham7159f572019-10-11 11:10:18 -07001462void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001463 int32_t sequenceId, hwc2_display_t /*display*/,
1464 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1465 Mutex::Autolock lock(mStateLock);
1466 if (sequenceId != getBE().mComposerSequenceId) {
1467 return;
1468 }
1469 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001470}
1471
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001472void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001473 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001474 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001476 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001477 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001478}
1479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001480void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001481 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001482
1483 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1484 // display power state.
1485 postMessageAsync(new LambdaMessage(
1486 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1487}
1488
1489void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1490 ATRACE_CALL();
1491
Ady Abraham27c70212019-06-11 10:52:26 -07001492 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1493
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001494 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001495 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1496 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001497 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001498 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001499 }
Mathias Agopian86303202012-07-24 22:46:10 -07001500}
1501
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001502// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001503void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001504 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001505 // Clear the drawing state so that the logic inside of
1506 // handleTransactionLocked will fire. It will determine the delta between
1507 // mCurrentState and mDrawingState and re-apply all changes when we make the
1508 // transition.
1509 mDrawingState.displays.clear();
1510 mDisplays.clear();
1511}
1512
Steven Thomas050b2c82017-03-06 11:45:16 -08001513void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001514 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001515 if (!mVrFlinger)
1516 return;
1517 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001518 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001519 return;
1520 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001521
Lloyd Pique441d5042018-10-18 16:49:51 -07001522 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 ALOGE("Vr flinger is only supported for remote hardware composer"
1524 " service connections. Ignoring request to transition to vr"
1525 " flinger.");
1526 mVrFlingerRequestsDisplay = false;
1527 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001528 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001529
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomas0123ac62018-07-12 11:32:34 -07001532 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001533 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001534
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001535 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001536
1537 // Clear out all the output layers from the composition engine for all
1538 // displays before destroying the hardware composer interface. This ensures
1539 // any HWC layers are destroyed through that interface before it becomes
1540 // invalid.
1541 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001542 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001543 }
1544
Steven Thomas0123ac62018-07-12 11:32:34 -07001545 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1546 // called below. Clear the reference now so we don't accidentally use it
1547 // later.
1548 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001551 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001552 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001553
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001555 // Delete the current instance before creating the new one
1556 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1557 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1558 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1559 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001560
Lloyd Pique441d5042018-10-18 16:49:51 -07001561 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001562 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001563
1564 if (vrFlingerRequestsDisplay) {
1565 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001567
1568 mVisibleRegionsDirty = true;
1569 invalidateHwcGeometry();
1570
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001571 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001572 display = getDefaultDisplayDeviceLocked();
1573 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001574 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001575
Steven Thomasb02664d2017-07-26 18:48:28 -07001576 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001577 const nsecs_t vsyncPeriod = getVsyncPeriod();
1578 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001579
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001580 // The present fences returned from vr_hwc are not an accurate
1581 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001582 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001583
Steven Thomasb02664d2017-07-26 18:48:28 -07001584 // Use phase of 0 since phase is not known.
1585 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001586 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001587 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001588
Ana Krulecc2870422019-01-29 19:00:58 -08001589 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001590
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001591 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001592 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593}
1594
Ady Abraham11579302019-09-19 12:35:58 -07001595bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1596 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001597 // We are storing the last 2 present fences. If sf's phase offset is to be
1598 // woken up before the actual vsync but targeting the next vsync, we need to check
1599 // fence N-2
1600 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001601 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001602 ? mPreviousPresentFences[0]
1603 : mPreviousPresentFences[1];
1604
Ady Abraham11579302019-09-19 12:35:58 -07001605 if (fence == Fence::NO_FENCE) {
1606 return false;
1607 }
1608
1609 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1610 fence->wait(graceTimeMs);
1611 }
1612
1613 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001614}
1615
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001616void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001617 DisplayStatInfo stats;
1618 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001619 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001620 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001621 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001622 mPhaseOffsets->getOffsetThresholdForNextVsync()
1623 ? presentTime
1624 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001625}
1626
Dominik Laskowski22488f62019-03-28 09:53:04 -07001627void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001628 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001629 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001630 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001631 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001632 // calculate the expected present time once and use the cached
1633 // value throughout this frame to make sure all layers are
1634 // seeing this same value.
1635 populateExpectedPresentTime();
1636
Ady Abraham11579302019-09-19 12:35:58 -07001637 // When Backpressure propagation is enabled we want to give a small grace period
1638 // for the present fence to fire instead of just giving up on this frame to handle cases
1639 // where present fence is just about to get signaled.
1640 const int graceTimeForPresentFenceMs =
1641 (mPropagateBackpressure &&
1642 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1643 ? 1
1644 : 0;
1645 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1646 previousFrameMissed(
1647 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001648 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1649 mHadDeviceComposition && frameMissed};
1650 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1651 mHadClientComposition && frameMissed};
1652
Alec Mouricc0fc602019-02-26 21:45:19 -08001653 if (frameMissed) {
1654 mFrameMissedCount++;
1655 mTimeStats->incrementMissedFrames();
1656 }
1657
Alec Mouri40189b02019-03-05 15:07:54 -08001658 if (hwcFrameMissed) {
1659 mHwcFrameMissedCount++;
1660 }
1661
1662 if (gpuFrameMissed) {
1663 mGpuFrameMissedCount++;
1664 }
1665
Dominik Laskowski49cea512019-11-12 14:13:23 -08001666 mScheduler->chooseRefreshRateForContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001667
Ady Abrahamb838aed2019-02-12 15:30:16 -08001668 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001669 break;
1670 }
1671
Ady Abrahamadb9a992019-09-19 21:21:55 +00001672 if (frameMissed && mPropagateBackpressure) {
1673 if ((hwcFrameMissed && !gpuFrameMissed) ||
1674 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001675 signalLayerUpdate();
1676 break;
1677 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001678 }
Dan Stoza50182882016-07-08 12:02:20 -07001679
Steven Thomas050b2c82017-03-06 11:45:16 -08001680 // Now that we're going to make it to the handleMessageTransaction()
1681 // call below it's safe to call updateVrFlinger(), which will
1682 // potentially trigger a display handoff.
1683 updateVrFlinger();
1684
Dan Stoza6b9454d2014-11-07 16:00:59 -08001685 bool refreshNeeded = handleMessageTransaction();
1686 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001687
1688 updateCursorAsync();
1689 updateInputFlinger();
1690
Dan Stoza58784442014-12-02 16:58:17 -08001691 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001692 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001693 // Signal a refresh if a transaction modified the window state,
1694 // a new buffer was latched, or if HWC has requested a full
1695 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001696 if (mFrameStartTime <= 0) {
1697 // We should only use the time of the first invalidate
1698 // message that signals a refresh as the beginning of the
1699 // frame. Otherwise the real frame time will be
1700 // underestimated.
1701 mFrameStartTime = frameStart;
1702 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001703 signalRefresh();
1704 }
1705 break;
1706 }
1707 case MessageQueue::REFRESH: {
1708 handleMessageRefresh();
1709 break;
1710 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001711 }
1712}
1713
Dan Stoza6b9454d2014-11-07 16:00:59 -08001714bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001715 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001716 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001717
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001718 bool flushedATransaction = flushTransactionQueues();
1719
1720 bool runHandleTransaction = transactionFlags &&
1721 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1722
1723 if (runHandleTransaction) {
1724 handleTransaction(eTransactionMask);
1725 } else {
1726 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001727 }
1728
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001729 if (transactionFlushNeeded()) {
1730 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001731 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001732
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001733 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001734}
1735
Mathias Agopian4fec8732012-06-29 14:12:52 -07001736void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001737 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001738
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001739 mRefreshPending = false;
1740
Lloyd Piqueab039b52019-02-13 14:22:42 -08001741 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001742 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001743 for (const auto& [_, display] : mDisplays) {
1744 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1745 }
1746 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1747 auto compositionLayer = layer->getCompositionLayer();
1748 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1749 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001750 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1751 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1752 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001753 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001754 }
1755
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001756 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001757 refreshArgs.outputColorSetting = useColorManagement
1758 ? mDisplayColorSetting
1759 : compositionengine::OutputColorSetting::kUnmanaged;
1760 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1761 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001762
1763 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1764 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001765
1766 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1767 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1768 mDrawingState.colorMatrixChanged = false;
1769 }
1770
1771 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1772
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001773 if (mDebugRegion != 0) {
1774 refreshArgs.devOptFlashDirtyRegionsDelay =
1775 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1776 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001777
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001778 mGeometryInvalid = false;
1779
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001780 // Store the present time just before calling to the composition engine so we could notify
1781 // the scheduler.
1782 const auto presentTime = systemTime();
1783
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001784 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001785 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1786 // Reset the frame start time now that we've recorded this frame.
1787 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001788
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001789 mScheduler->onDisplayRefreshed(presentTime);
1790
David Sodmanfa9b2af2017-12-24 13:28:59 -08001791 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001792 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001793
Lloyd Pique66d68602019-02-13 14:23:31 -08001794 mHadClientComposition =
1795 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1796 auto& displayDevice = tokenDisplayPair.second;
1797 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1798 });
1799 mHadDeviceComposition =
1800 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1801 auto& displayDevice = tokenDisplayPair.second;
1802 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1803 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001804
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001805 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001806
David Sodman7e4ae112018-02-09 15:02:28 -08001807 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001808 if (mVisibleRegionsDirty) {
1809 mVisibleRegionsDirty = false;
1810 if (mTracingEnabled) {
1811 mTracing.notify("visibleRegionsDirty");
1812 }
1813 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001814
1815 if (mCompositionEngine->needsAnotherUpdate()) {
1816 signalLayerUpdate();
1817 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001819
David Sodmanfa9b2af2017-12-24 13:28:59 -08001820
1821bool SurfaceFlinger::handleMessageInvalidate() {
1822 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001823 bool refreshNeeded = handlePageFlip();
1824
Vishnu Nair4351ad52019-02-11 14:13:02 -08001825 if (mVisibleRegionsDirty) {
1826 computeLayerBounds();
1827 }
1828
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001829 for (auto& layer : mLayersPendingRefresh) {
1830 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001831 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001832 invalidateLayerStack(layer, visibleReg);
1833 }
1834 mLayersPendingRefresh.clear();
1835 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001836}
1837
Ana Krulece588e312018-09-18 12:32:24 -07001838void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1839 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840 // Update queue of past composite+present times and determine the
1841 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001842 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001843 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001844 while (!getBE().mCompositePresentTimes.empty()) {
1845 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001846 // Cached values should have been updated before calling this method,
1847 // which helps avoid duplicate syscalls.
1848 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1849 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1850 break;
1851 }
1852 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001853 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001854 }
1855
1856 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001857 while (getBE().mCompositePresentTimes.size() > 16) {
1858 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001859 }
1860
Ana Krulece588e312018-09-18 12:32:24 -07001861 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001862}
1863
Ana Krulece588e312018-09-18 12:32:24 -07001864void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1865 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001866 // Integer division and modulo round toward 0 not -inf, so we need to
1867 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001868 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1869 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1870 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871
Ana Krulec757f63a2019-01-25 10:46:18 -08001872 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001873 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001874 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001875 }
1876
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001877 // Snap the latency to a value that removes scheduling jitter from the
1878 // composition and present times, which often have >1ms of jitter.
1879 // Reducing jitter is important if an app attempts to extrapolate
1880 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001881 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001882 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001883 nsecs_t bias = stats.vsyncPeriod / 2;
1884 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1885 nsecs_t snappedCompositeToPresentLatency =
1886 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001887
David Sodman99974d22017-11-28 12:04:33 -08001888 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001889 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1890 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001891 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001892}
1893
David Sodman2b406362017-12-15 13:33:47 -08001894void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001895{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 ATRACE_CALL();
1897 ALOGV("postComposition");
1898
Brian Anderson3546a3f2016-07-14 11:51:14 -07001899 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001900 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001901 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001902 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001903 }
1904
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001905 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001906 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001907
David Sodman73beded2017-11-15 11:56:06 -08001908 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001909 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001910 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001911 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001912 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1913 ->getRenderSurface()
1914 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001915 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001916 } else {
1917 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1918 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001919
David Sodman73beded2017-11-15 11:56:06 -08001920 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001921 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1922 mPreviousPresentFences[0] = displayDevice
1923 ? getHwComposer().getPresentFence(*displayDevice->getId())
1924 : Fence::NO_FENCE;
1925 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001926 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001927
Ana Krulece588e312018-09-18 12:32:24 -07001928 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001929 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001930
Lloyd Piqueab039b52019-02-13 14:22:42 -08001931 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1932 // be sampled a little later than when we started doing work for this frame,
1933 // but that should be okay since updateCompositorTiming has snapping logic.
1934 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1935 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001936 CompositorTiming compositorTiming;
1937 {
David Sodman99974d22017-11-28 12:04:33 -08001938 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1939 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001940 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941
Robert Carr2047fae2016-11-28 14:09:09 -08001942 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08001943 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
1944 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001945 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001946 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001947 }
Robert Carr2047fae2016-11-28 14:09:09 -08001948 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001949
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001950 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001951 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001952 }
1953
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001954 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001955 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1956 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001957 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001958 }
1959 }
1960
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001961 if (mAnimCompositionPending) {
1962 mAnimCompositionPending = false;
1963
Brian Anderson4e606e32017-03-16 15:34:57 -07001964 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001965 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001966 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001967 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001968 // The HWC doesn't support present fences, so use the refresh
1969 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001970 const nsecs_t presentTime =
1971 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001972 mAnimFrameTracker.setActualPresentTime(presentTime);
1973 }
1974 mAnimFrameTracker.advanceFrame();
1975 }
Dan Stozab90cf072015-03-05 11:05:59 -08001976
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001977 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001978 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001979 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001980 }
1981
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001982 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001983
Lloyd Pique32cbe282018-10-19 13:09:22 -07001984 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1985 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001986 return;
1987 }
1988
1989 nsecs_t currentTime = systemTime();
1990 if (mHasPoweredOff) {
1991 mHasPoweredOff = false;
1992 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001993 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001994 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001995 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1996 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001997 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001998 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001999 }
David Sodman4a36e932017-11-07 14:29:47 -08002000 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002001 }
David Sodman4a36e932017-11-07 14:29:47 -08002002 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002003
2004 {
2005 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002006 if (mTexturePool.size() < mTexturePoolSize) {
2007 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002008 const size_t offset = mTexturePool.size();
2009 mTexturePool.resize(mTexturePoolSize);
2010 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2011 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002012 } else if (mTexturePool.size() > mTexturePoolSize) {
2013 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2014 const size_t offset = mTexturePoolSize;
2015 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2016 mTexturePool.resize(mTexturePoolSize);
2017 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002018 }
2019 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002020
Ady Abrahambe0f9482019-04-24 15:41:53 -07002021 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002022 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002023
Kevin DuBois413287f2019-02-25 08:46:47 -08002024 if (mLumaSampling && mRegionSamplingThread) {
2025 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002026 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002027
2028 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2029 // side-effect of getTotalSize(), so we check that again here
2030 if (ATRACE_ENABLED()) {
2031 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2032 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002033}
2034
Vishnu Nair4351ad52019-02-11 14:13:02 -08002035void SurfaceFlinger::computeLayerBounds() {
2036 for (const auto& pair : mDisplays) {
2037 const auto& displayDevice = pair.second;
2038 const auto display = displayDevice->getCompositionDisplay();
2039 for (const auto& layer : mDrawingState.layersSortedByZ) {
2040 // only consider the layers on the given layer stack
2041 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002042 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002043 }
2044
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002045 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2046 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002047 }
2048 }
2049}
2050
David Sodmanfa9b2af2017-12-24 13:28:59 -08002051void SurfaceFlinger::postFrame()
2052{
2053 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002054 const auto display = getDefaultDisplayDeviceLocked();
2055 if (display && getHwComposer().isConnected(*display->getId())) {
2056 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002057 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2058 logFrameStats();
2059 }
2060 }
2061}
2062
Mathias Agopian87baae12012-07-31 12:38:26 -07002063void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002064{
Mathias Agopian841cde52012-03-01 15:44:37 -08002065 ATRACE_CALL();
2066
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002067 // here we keep a copy of the drawing state (that is the state that's
2068 // going to be overwritten by handleTransactionLocked()) outside of
2069 // mStateLock so that the side-effects of the State assignment
2070 // don't happen with mStateLock held (which can cause deadlocks).
2071 State drawingState(mDrawingState);
2072
Mathias Agopianca4d3602011-05-19 15:38:14 -07002073 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002074 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002075
Mathias Agopianca4d3602011-05-19 15:38:14 -07002076 // Here we're guaranteed that some transaction flags are set
2077 // so we can call handleTransactionLocked() unconditionally.
2078 // We call getTransactionFlags(), which will also clear the flags,
2079 // with mStateLock held to guarantee that mCurrentState won't change
2080 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002081
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002082 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002083 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002084 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002085
Mathias Agopianca4d3602011-05-19 15:38:14 -07002086 mDebugInTransaction = 0;
2087 invalidateHwcGeometry();
2088 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002089}
2090
Lloyd Piqueba04e622017-12-14 17:11:26 -08002091void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2092 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002093 const std::optional<DisplayIdentificationInfo> info =
2094 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002095
Dominik Laskowski075d3172018-05-24 15:50:06 -07002096 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002097 continue;
2098 }
2099
Lloyd Piqueba04e622017-12-14 17:11:26 -08002100 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002101 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002102 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002103 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2104 initScheduler(info->id);
2105 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002106 mPhysicalDisplayTokens[info->id] = new BBinder();
2107 DisplayDeviceState state;
2108 state.displayId = info->id;
2109 state.isSecure = true; // All physical displays are currently considered secure.
2110 state.displayName = info->name;
2111 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2112 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002113 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002114 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002115 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002116
Dominik Laskowski075d3172018-05-24 15:50:06 -07002117 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2118 if (index >= 0) {
2119 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2120 mInterceptor->saveDisplayDeletion(state.sequenceId);
2121 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002122 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002123 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002124 }
2125
2126 processDisplayChangesLocked();
2127 }
2128
2129 mPendingHotplugEvents.clear();
2130}
2131
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002132void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002133 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2134 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002135}
2136
Lloyd Pique99d3da52018-01-22 17:48:03 -08002137sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002138 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002139 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002140 const sp<IGraphicBufferProducer>& producer) {
2141 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002142 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002143 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002144 creationArgs.isSecure = state.isSecure;
2145 creationArgs.displaySurface = dispSurface;
2146 creationArgs.hasWideColorGamut = false;
2147 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002148 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002149
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002150 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002151 creationArgs.isPrimary = isInternalDisplay;
2152
2153 if (useColorManagement && displayId) {
2154 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002155 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002156 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002157 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002158 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002159
Dominik Laskowski7e045462018-05-30 13:02:02 -07002160 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002161 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002162 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002163 }
tangrobin6753a022018-08-10 10:58:54 +08002164 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002165
Dominik Laskowski075d3172018-05-24 15:50:06 -07002166 if (displayId) {
2167 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002168 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002169 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002170 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002171
Lloyd Pique90c115d2018-09-18 21:39:42 -07002172 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002173 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002174 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002175
Lloyd Pique99d3da52018-01-22 17:48:03 -08002176 // Make sure that composition can never be stalled by a virtual display
2177 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002178 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002179 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002180 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2181 }
2182
Dominik Laskowski075d3172018-05-24 15:50:06 -07002183 creationArgs.displayInstallOrientation =
2184 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002185
Lloyd Pique99d3da52018-01-22 17:48:03 -08002186 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002187 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002188
Lloyd Pique90c115d2018-09-18 21:39:42 -07002189 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002190
2191 if (maxFrameBufferAcquiredBuffers >= 3) {
2192 nativeWindowSurface->preallocateBuffers();
2193 }
2194
2195 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002196 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002197 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002198 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002199 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002200 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002201 display->getCompositionDisplay()->setColorProfile(
2202 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2203 RenderIntent::COLORIMETRIC,
2204 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002205 if (!state.isVirtual()) {
2206 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002207 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2208 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002209 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002210
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002211 display->setLayerStack(state.layerStack);
2212 display->setProjection(state.orientation, state.viewport, state.frame);
2213 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002214
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002215 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002216}
2217
Lloyd Pique347200f2017-12-14 17:00:15 -08002218void SurfaceFlinger::processDisplayChangesLocked() {
2219 // here we take advantage of Vector's copy-on-write semantics to
2220 // improve performance by skipping the transaction entirely when
2221 // know that the lists are identical
2222 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2223 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2224 if (!curr.isIdenticalTo(draw)) {
2225 mVisibleRegionsDirty = true;
2226 const size_t cc = curr.size();
2227 size_t dc = draw.size();
2228
2229 // find the displays that were removed
2230 // (ie: in drawing state but not in current state)
2231 // also handle displays that changed
2232 // (ie: displays that are in both lists)
2233 for (size_t i = 0; i < dc;) {
2234 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2235 if (j < 0) {
2236 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002237 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002238 // Save display ID before disconnecting.
2239 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002240 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002241
2242 if (!display->isVirtual()) {
2243 LOG_ALWAYS_FATAL_IF(!displayId);
2244 dispatchDisplayHotplugEvent(displayId->value, false);
2245 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002246 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002247
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002248 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002249 } else {
2250 // this display is in both lists. see if something changed.
2251 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002252 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002253 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2254 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2255 if (state_binder != draw_binder) {
2256 // changing the surface is like destroying and
2257 // recreating the DisplayDevice, so we just remove it
2258 // from the drawing state, so that it get re-added
2259 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002260 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002261 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002262 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002263 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002264 mDrawingState.displays.removeItemsAt(i);
2265 dc--;
2266 // at this point we must loop to the next item
2267 continue;
2268 }
2269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002270 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002271 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002272 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002273 }
2274 if ((state.orientation != draw[i].orientation) ||
2275 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002277 }
2278 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002280 }
2281 }
2282 }
2283 ++i;
2284 }
2285
2286 // find displays that were added
2287 // (ie: in current state but not in drawing state)
2288 for (size_t i = 0; i < cc; i++) {
2289 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2290 const DisplayDeviceState& state(curr[i]);
2291
Lloyd Pique542307f2018-10-19 13:24:08 -07002292 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002293 sp<IGraphicBufferProducer> producer;
2294 sp<IGraphicBufferProducer> bqProducer;
2295 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002296 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002297
Dominik Laskowski075d3172018-05-24 15:50:06 -07002298 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002299 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002300 // Virtual displays without a surface are dormant:
2301 // they have external state (layer stack, projection,
2302 // etc.) but no internal state (i.e. a DisplayDevice).
2303 if (state.surface != nullptr) {
2304 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002305 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002306 int width = 0;
2307 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2308 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2309 int height = 0;
2310 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2311 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2312 int intFormat = 0;
2313 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2314 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002315 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002316
Dominik Laskowski075d3172018-05-24 15:50:06 -07002317 displayId =
2318 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002319 }
2320
2321 // TODO: Plumb requested format back up to consumer
2322
2323 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002324 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002325 bqProducer, bqConsumer,
2326 state.displayName);
2327
2328 dispSurface = vds;
2329 producer = vds;
2330 }
2331 } else {
2332 ALOGE_IF(state.surface != nullptr,
2333 "adding a supported display, but rendering "
2334 "surface is provided (%p), ignoring it",
2335 state.surface.get());
2336
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 displayId = state.displayId;
2338 LOG_ALWAYS_FATAL_IF(!displayId);
2339 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002340 producer = bqProducer;
2341 }
2342
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002343 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002344 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002345 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002346 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002347 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002348 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002349 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002350 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 }
2352 }
2353 }
2354 }
2355 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002356
2357 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002358}
2359
Mathias Agopian87baae12012-07-31 12:38:26 -07002360void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002361{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002362 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2363
Dan Stoza7dde5992015-05-22 09:51:44 -07002364 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002365 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2366 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002367 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002368
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369 /*
2370 * Traversal of the children
2371 * (perform the transaction for each of them if needed)
2372 */
2373
Marissa Wall06255332019-03-27 13:48:27 -07002374 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002375 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002376 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002377 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002378
2379 const uint32_t flags = layer->doTransaction(0);
2380 if (flags & Layer::eVisibleRegion)
2381 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002382
2383 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002384 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002385 }
Robert Carr2047fae2016-11-28 14:09:09 -08002386 });
Marissa Wall06255332019-03-27 13:48:27 -07002387 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002388 }
2389
2390 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002391 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 */
2393
Mathias Agopiane57f2922012-08-09 16:29:12 -07002394 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002395 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002396 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002397 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002398
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002399 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002400 // The transform hint might have changed for some layers
2401 // (either because a display has changed, or because a layer
2402 // as changed).
2403 //
2404 // Walk through all the layers in currentLayers,
2405 // and update their transform hint.
2406 //
2407 // If a layer is visible only on a single display, then that
2408 // display is used to calculate the hint, otherwise we use the
2409 // default display.
2410 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002411 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002412 // the hint is set before we acquire a buffer from the surface texture.
2413 //
2414 // NOTE: layer transactions have taken place already, so we use their
2415 // drawing state. However, SurfaceFlinger's own transaction has not
2416 // happened yet, so we must use the current state layer list
2417 // (soon to become the drawing state list).
2418 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002419 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002420 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002421 bool first = true;
2422 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002423 // NOTE: we rely on the fact that layers are sorted by
2424 // layerStack first (so we don't have to traverse the list
2425 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002426 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002427 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002428 currentlayerStack = layerStack;
2429 // figure out if this layerstack is mirrored
2430 // (more than one display) if so, pick the default display,
2431 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002432 hintDisplay = nullptr;
2433 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002434 if (display->getCompositionDisplay()
2435 ->belongsInOutput(layer->getLayerStack(),
2436 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002437 if (hintDisplay) {
2438 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002439 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002441 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002442 }
2443 }
2444 }
2445 }
Chet Haase91d25932013-04-11 15:24:55 -07002446
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002447 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002448 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2449 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002450
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002451 // could be null when this layer is using a layerStack
2452 // that is not visible on any display. Also can occur at
2453 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002454 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002455 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002456
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002457 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002458 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002459 if (hintDisplay) {
2460 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002461 }
Robert Carr2047fae2016-11-28 14:09:09 -08002462
2463 first = false;
2464 });
Mathias Agopian84300952012-11-21 16:02:13 -08002465 }
2466
2467
Mathias Agopian3559b072012-08-15 13:46:03 -07002468 /*
2469 * Perform our own transaction if needed
2470 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002471
2472 if (mLayersAdded) {
2473 mLayersAdded = false;
2474 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002475 mVisibleRegionsDirty = true;
2476 }
2477
2478 // some layers might have been removed, so
2479 // we need to update the regions they're exposing.
2480 if (mLayersRemoved) {
2481 mLayersRemoved = false;
2482 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002483 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002484 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002485 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002486 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002487 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002488 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002489 }
Robert Carr2047fae2016-11-28 14:09:09 -08002490 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002491 }
2492
Vishnu Nairec0ab382019-02-13 15:32:56 -08002493 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002494 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002495}
2496
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002497void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002498 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002499 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002500 return;
2501 }
2502
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002503 if (mVisibleRegionsDirty || mInputInfoChanged) {
2504 mInputInfoChanged = false;
2505 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002506 } else if (mInputWindowCommands.syncInputWindows) {
2507 // If the caller requested to sync input windows, but there are no
2508 // changes to input windows, notify immediately.
2509 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002510 }
2511
Arthur Hung6cbb9752019-09-05 16:38:18 +08002512 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002513}
2514
2515void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002516 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002517
2518 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2519 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002520 // When calculating the screen bounds we ignore the transparent region since it may
2521 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002522 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002523 }
2524 });
chaviw291d88a2019-02-14 10:33:58 -08002525
2526 mInputFlinger->setInputWindows(inputHandles,
2527 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2528 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002529}
2530
Vishnu Nairec0ab382019-02-13 15:32:56 -08002531void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002532 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002533 mPendingInputWindowCommands.clear();
2534}
2535
Riley Andrews03414a12014-07-01 14:22:59 -07002536void SurfaceFlinger::updateCursorAsync()
2537{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002538 compositionengine::CompositionRefreshArgs refreshArgs;
2539 for (const auto& [_, display] : mDisplays) {
2540 if (display->getId()) {
2541 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002542 }
2543 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002544
2545 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002546}
2547
Ady Abraham2139f732019-11-13 18:56:40 -08002548void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2549 Scheduler::ConfigEvent event) {
2550 Mutex::Autolock lock(mStateLock);
2551 changeRefreshRateLocked(refreshRate, event);
2552}
2553
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002554void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2555 if (mScheduler) {
2556 // In practice it's not allowed to hotplug in/out the primary display once it's been
2557 // connected during startup, but some tests do it, so just warn and return.
2558 ALOGW("Can't re-init scheduler");
2559 return;
2560 }
2561
Ady Abraham2139f732019-11-13 18:56:40 -08002562 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002563 mRefreshRateConfigs =
2564 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2565 getHwComposer().getConfigs(
2566 primaryDisplayId),
2567 currentConfig);
2568 mRefreshRateStats =
2569 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2570 currentConfig, HWC_POWER_MODE_OFF);
2571 mRefreshRateStats->setConfigMode(currentConfig);
2572
2573 // start the EventThread
2574 mScheduler =
2575 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002576 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002577 mAppConnectionHandle =
2578 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2579 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2580 impl::EventThread::InterceptVSyncsCallback());
2581 mSfConnectionHandle =
2582 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2583 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2584 [this](nsecs_t timestamp) {
2585 mInterceptor->saveVSyncEvent(timestamp);
2586 });
2587
2588 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2589 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2590 mPhaseOffsets->getCurrentOffsets());
2591
2592 mRegionSamplingThread =
2593 new RegionSamplingThread(*this, *mScheduler,
2594 RegionSamplingThread::EnvironmentTimingTunables());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002595}
2596
Mathias Agopian4fec8732012-06-29 14:12:52 -07002597void SurfaceFlinger::commitTransaction()
2598{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002599 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002600
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002601 mTransactionPending = false;
2602 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002603 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002604}
2605
Lloyd Pique58e24a32019-08-01 15:50:14 -07002606void SurfaceFlinger::commitTransactionLocked() {
2607 if (!mLayersPendingRemoval.isEmpty()) {
2608 // Notify removed layers now that they can't be drawn from
2609 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002610 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002611
2612 // Ensure any buffers set to display on any children are released.
2613 if (l->isRemovedFromCurrentState()) {
2614 l->latchAndReleaseBuffer();
2615 }
2616
2617 // If the layer has been removed and has no parent, then it will not be reachable
2618 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2619 // ensure we can copy its current to drawing state.
2620 if (!l->getParent()) {
2621 mOffscreenLayers.emplace(l.get());
2622 }
2623 }
2624 mLayersPendingRemoval.clear();
2625 }
2626
2627 // If this transaction is part of a window animation then the next frame
2628 // we composite should be considered an animation as well.
2629 mAnimCompositionPending = mAnimTransactionPending;
2630
2631 mDrawingState = mCurrentState;
2632 // clear the "changed" flags in current state
2633 mCurrentState.colorMatrixChanged = false;
2634
2635 mDrawingState.traverseInZOrder([&](Layer* layer) {
2636 layer->commitChildList();
2637
2638 // If the layer can be reached when traversing mDrawingState, then the layer is no
2639 // longer offscreen. Remove the layer from the offscreenLayer set.
2640 if (mOffscreenLayers.count(layer)) {
2641 mOffscreenLayers.erase(layer);
2642 }
2643 });
2644
2645 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002646 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002647}
2648
Nataniel Borges2b796da2019-02-15 13:32:18 -08002649void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2650 if (mTracingEnabledChanged) {
2651 mTracingEnabled = mTracing.isEnabled();
2652 mTracingEnabledChanged = false;
2653 }
2654
2655 // Synchronize with Tracing thread
2656 std::unique_lock<std::mutex> lock;
2657 if (mTracingEnabled) {
2658 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2659 }
2660
2661 lockedOperation();
2662
2663 // Synchronize with Tracing thread
2664 if (mTracingEnabled) {
2665 lock.unlock();
2666 }
2667}
2668
chaviw74d90ad2019-04-26 14:45:26 -07002669void SurfaceFlinger::commitOffscreenLayers() {
2670 for (Layer* offscreenLayer : mOffscreenLayers) {
2671 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2672 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2673 if (!trFlags) return;
2674
2675 layer->doTransaction(0);
2676 layer->commitChildList();
2677 });
2678 }
2679}
2680
Chia-I Wuab0c3192017-08-01 11:29:00 -07002681void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002682 for (const auto& [token, displayDevice] : mDisplays) {
2683 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002684 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002685 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002686 }
2687 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002688}
2689
Dan Stoza6b9454d2014-11-07 16:00:59 -08002690bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691{
Ady Abraham09bd3922019-04-08 10:44:56 -07002692 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002693 ALOGV("handlePageFlip");
2694
Brian Andersond6927fb2016-07-23 23:37:30 -07002695 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696
Mathias Agopian4fec8732012-06-29 14:12:52 -07002697 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002698 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002699 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002700
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002701 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2702
Eric Penner51c59cd2014-07-28 19:51:58 -07002703 // Store the set of layers that need updates. This set must not change as
2704 // buffers are being latched, as this could result in a deadlock.
2705 // Example: Two producers share the same command stream and:
2706 // 1.) Layer 0 is latched
2707 // 2.) Layer 0 gets a new frame
2708 // 2.) Layer 1 gets a new frame
2709 // 3.) Layer 1 is latched.
2710 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2711 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002712 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002713 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002714 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002715 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002716 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002717 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002718 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002719 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002720 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002721 } else {
2722 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002723 }
Robert Carr2047fae2016-11-28 14:09:09 -08002724 });
2725
chaviw49a108c2019-08-12 11:23:06 -07002726 // The client can continue submitting buffers for offscreen layers, but they will not
2727 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2728 // layers to ensure dequeueBuffer doesn't block indefinitely.
2729 for (Layer* offscreenLayer : mOffscreenLayers) {
2730 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2731 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2732 }
2733
Lloyd Piquef2c79392018-12-20 16:23:33 -08002734 if (!mLayersWithQueuedFrames.empty()) {
2735 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2736 // writes to Layer current state. See also b/119481871
2737 Mutex::Autolock lock(mStateLock);
2738
2739 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002740 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002741 mLayersPendingRefresh.push_back(layer);
2742 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002743 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002744 if (layer->isBufferLatched()) {
2745 newDataLatched = true;
2746 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002747 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002748 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002749
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002750 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002751
2752 // If we will need to wake up at some time in the future to deal with a
2753 // queued frame that shouldn't be displayed during this vsync period, wake
2754 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002755 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002756 signalLayerUpdate();
2757 }
2758
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002759 // enter boot animation on first buffer latch
2760 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2761 ALOGI("Enter boot animation");
2762 mBootStage = BootStage::BOOTANIMATION;
2763 }
2764
chaviw74b03172019-08-19 11:09:03 -07002765 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2766
Dan Stoza6b9454d2014-11-07 16:00:59 -08002767 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002768 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002769}
2770
Mathias Agopianad456f92011-01-13 17:53:01 -08002771void SurfaceFlinger::invalidateHwcGeometry()
2772{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002773 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002774}
2775
Robert Carrc0df3122019-04-11 13:18:21 -07002776status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2777 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2778 const sp<IBinder>& parentHandle,
2779 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002780 // add this layer to the current state list
2781 {
2782 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002783 sp<Layer> parent;
2784 if (parentHandle != nullptr) {
2785 parent = fromHandle(parentHandle);
2786 if (parent == nullptr) {
2787 return NAME_NOT_FOUND;
2788 }
2789 } else {
2790 parent = parentLayer;
2791 }
2792
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002794 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002795 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002796 return NO_MEMORY;
2797 }
Robert Carrc0df3122019-04-11 13:18:21 -07002798
2799 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2800
Robert Carrb89ea9d2018-12-10 13:01:14 -08002801 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002802 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002803 } else if (parent == nullptr) {
2804 lbc->onRemovedFromCurrentState();
2805 } else if (parent->isRemovedFromCurrentState()) {
2806 parent->addChild(lbc);
2807 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002808 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002809 parent->addChild(lbc);
2810 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002811
Yiwei Zhang243b3782018-05-15 17:40:04 -07002812 if (gbc != nullptr) {
2813 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2814 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2815 mMaxGraphicBufferProducerListSize,
2816 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2817 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002818 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002819 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002821 }
2822
Mathias Agopian96f08192010-06-02 23:28:45 -07002823 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002824 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002825
Dan Stoza7d89d062015-04-30 13:29:25 -07002826 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002827}
2828
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002829uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002830 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002831}
2832
Mathias Agopian3f844832013-08-07 21:24:32 -07002833uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002834 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835}
2836
Mathias Agopian3f844832013-08-07 21:24:32 -07002837uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002838 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002839}
2840
2841uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002842 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002843 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002844 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002845 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002846 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002847 }
2848 return old;
2849}
2850
Marissa Wall713b63f2018-10-17 15:42:43 -07002851bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002852 // to prevent onHandleDestroyed from being called while the lock is held,
2853 // we must keep a copy of the transactions (specifically the composer
2854 // states) around outside the scope of the lock
2855 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002856 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002857 {
2858 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002859
Valerie Haufce31b82019-04-30 16:41:14 -07002860 auto it = mTransactionQueues.begin();
2861 while (it != mTransactionQueues.end()) {
2862 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002863
Valerie Haufce31b82019-04-30 16:41:14 -07002864 while (!transactionQueue.empty()) {
2865 const auto& transaction = transactionQueue.front();
2866 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002867 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002868 transaction.states)) {
2869 setTransactionFlags(eTransactionFlushNeeded);
2870 break;
2871 }
2872 transactions.push_back(transaction);
2873 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2874 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002875 transaction.buffer, transaction.postTime,
2876 transaction.privileged, transaction.hasListenerCallbacks,
2877 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002878 transactionQueue.pop();
2879 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002880 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002881
Valerie Haufce31b82019-04-30 16:41:14 -07002882 if (transactionQueue.empty()) {
2883 it = mTransactionQueues.erase(it);
2884 mTransactionCV.broadcast();
2885 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002886 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002887 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002888 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002889 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002890 return flushedATransaction;
2891}
2892
2893bool SurfaceFlinger::transactionFlushNeeded() {
2894 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002895}
2896
chaviwca27f252018-02-06 16:46:39 -08002897
Marissa Wall17b4e452018-12-26 16:32:34 -08002898bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002899 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002900 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002901 if (!useCachedExpectedPresentTime)
2902 populateExpectedPresentTime();
2903
2904 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002905 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2906 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2907 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2908 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2909 return false;
2910 }
2911
Marissa Wall713b63f2018-10-17 15:42:43 -07002912 for (const ComposerState& state : states) {
2913 const layer_state_t& s = state.state;
2914 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2915 continue;
2916 }
2917 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002918 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002919 }
2920 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002921 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002922}
2923
Valerie Hau9dab9732019-08-20 09:29:25 -07002924void SurfaceFlinger::setTransactionState(
2925 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2926 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2927 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2928 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002929 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002930
Valerie Haubc6ddb12019-03-08 11:10:15 -08002931 const int64_t postTime = systemTime();
2932
Robert Carr14167e02019-02-13 13:50:55 -08002933 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2934
Mathias Agopian698c0872011-06-28 19:09:31 -07002935 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002936
Marissa Wall713b63f2018-10-17 15:42:43 -07002937 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002938 auto itr = mTransactionQueues.find(applyToken);
2939 // if this is an animation frame, wait until prior animation frame has
2940 // been applied by SF
2941 if (flags & eAnimation) {
2942 while (itr != mTransactionQueues.end()) {
2943 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2944 if (CC_UNLIKELY(err != NO_ERROR)) {
2945 ALOGW_IF(err == TIMED_OUT,
2946 "setTransactionState timed out "
2947 "waiting for animation frame to apply");
2948 break;
2949 }
2950 itr = mTransactionQueues.find(applyToken);
2951 }
2952 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002953
2954 // Expected present time is computed and cached on invalidate, so it may be stale.
2955 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2956 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002957 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002958 uncacheBuffer, postTime, privileged,
2959 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002960 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002961 return;
2962 }
2963
Valerie Haubc6ddb12019-03-08 11:10:15 -08002964 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002965 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2966 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002967}
2968
Valerie Hau9dab9732019-08-20 09:29:25 -07002969void SurfaceFlinger::applyTransactionState(
2970 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2971 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2972 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2973 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2974 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002975 uint32_t transactionFlags = 0;
2976
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002977 if (flags & eAnimation) {
2978 // For window updates that are part of an animation we must wait for
2979 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002980 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002981 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002982 if (CC_UNLIKELY(err != NO_ERROR)) {
2983 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002984 // caller after a few seconds.
2985 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2986 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002987 mAnimTransactionPending = false;
2988 break;
2989 }
2990 }
2991 }
2992
chaviwca27f252018-02-06 16:46:39 -08002993 for (const DisplayState& display : displays) {
2994 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002995 }
2996
Valerie Hau9dab9732019-08-20 09:29:25 -07002997 // start and end registration for listeners w/ no surface so they can get their callback. Note
2998 // that listeners with SurfaceControls will start registration during setClientStateLocked
2999 // below.
3000 for (const auto& listener : listenerCallbacks) {
3001 mTransactionCompletedThread.startRegistration(listener);
3002 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003003 }
3004
Valerie Hau9dab9732019-08-20 09:29:25 -07003005 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003006 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003007 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003008 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3009 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003010 }
3011
Valerie Hau9dab9732019-08-20 09:29:25 -07003012 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003013 mTransactionCompletedThread.endRegistration(listenerCallback);
3014 }
3015
Marissa Walle2ffb422018-10-12 11:33:52 -07003016 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003017 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003018 mTransactionCompletedThread.sendCallbacks();
3019 }
3020 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003021
chaviw273171b2018-12-26 11:46:30 -08003022 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3023
Marissa Wall947d34e2019-03-29 14:03:53 -07003024 if (uncacheBuffer.isValid()) {
3025 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003026 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003027 }
3028
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003029 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3030 // anyway. This can be used as a flush mechanism for previous async transactions.
3031 // Empty animation transaction can be used to simulate back-pressure, so also force a
3032 // transaction for empty animation transactions.
3033 if (transactionFlags == 0 &&
3034 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003035 transactionFlags = eTransactionNeeded;
3036 }
3037
Marissa Wall06255332019-03-27 13:48:27 -07003038 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3039 // so we don't have to wake up again next frame to preform an uneeded traversal.
3040 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3041 transactionFlags = transactionFlags & (~eTraversalNeeded);
3042 mTraversalNeededMainThread = true;
3043 }
3044
Mathias Agopian386aa982011-11-07 21:58:03 -08003045 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003046 if (mInterceptor->isEnabled()) {
3047 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003048 }
Irvel468051e2016-06-13 16:44:44 -07003049
Mathias Agopian386aa982011-11-07 21:58:03 -08003050 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003051 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3052 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003053 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003054
3055 // if this is a synchronous transaction, wait for it to take effect
3056 // before returning.
3057 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003058 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003059 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003060 if (flags & eAnimation) {
3061 mAnimTransactionPending = true;
3062 }
chaviw4fe36852019-04-15 16:25:49 -07003063 if (mPendingInputWindowCommands.syncInputWindows) {
3064 mPendingSyncInputWindows = true;
3065 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003066
3067 // applyTransactionState can be called by either the main SF thread or by
3068 // another process through setTransactionState. While a given process may wish
3069 // to wait on synchronous transactions, the main SF thread should never
3070 // be blocked. Therefore, we only wait if isMainThread is false.
3071 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003072 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3073 if (CC_UNLIKELY(err != NO_ERROR)) {
3074 // just in case something goes wrong in SF, return to the
3075 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003076 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3077 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003078 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003079 break;
3080 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003081 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003082 }
3083}
3084
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003085uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3086 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3087 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003088
Mathias Agopiane57f2922012-08-09 16:29:12 -07003089 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003090 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3091
3092 const uint32_t what = s.what;
3093 if (what & DisplayState::eSurfaceChanged) {
3094 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3095 state.surface = s.surface;
3096 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003097 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003098 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003099 if (what & DisplayState::eLayerStackChanged) {
3100 if (state.layerStack != s.layerStack) {
3101 state.layerStack = s.layerStack;
3102 flags |= eDisplayTransactionNeeded;
3103 }
3104 }
3105 if (what & DisplayState::eDisplayProjectionChanged) {
3106 if (state.orientation != s.orientation) {
3107 state.orientation = s.orientation;
3108 flags |= eDisplayTransactionNeeded;
3109 }
3110 if (state.frame != s.frame) {
3111 state.frame = s.frame;
3112 flags |= eDisplayTransactionNeeded;
3113 }
3114 if (state.viewport != s.viewport) {
3115 state.viewport = s.viewport;
3116 flags |= eDisplayTransactionNeeded;
3117 }
3118 }
3119 if (what & DisplayState::eDisplaySizeChanged) {
3120 if (state.width != s.width) {
3121 state.width = s.width;
3122 flags |= eDisplayTransactionNeeded;
3123 }
3124 if (state.height != s.height) {
3125 state.height = s.height;
3126 flags |= eDisplayTransactionNeeded;
3127 }
3128 }
3129
Mathias Agopiane57f2922012-08-09 16:29:12 -07003130 return flags;
3131}
3132
Robert Carr14167e02019-02-13 13:50:55 -08003133bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003134 IPCThreadState* ipc = IPCThreadState::self();
3135 const int pid = ipc->getCallingPid();
3136 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003137 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003138 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003139 return false;
3140 }
3141 return true;
3142}
3143
Marissa Wall3dad52d2019-03-22 14:03:19 -07003144uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003145 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3146 bool privileged,
3147 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003148 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003149
Valerie Hau9dab9732019-08-20 09:29:25 -07003150 for (auto& listener : s.listeners) {
3151 // note that startRegistration will not re-register if the listener has
3152 // already be registered for a prior surface control
3153 mTransactionCompletedThread.startRegistration(listener);
3154 listenerCallbacks.insert(listener);
3155 }
3156
Vishnu Nairf03652d2019-07-16 17:56:56 -07003157 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003158 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003159 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003160 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003161 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003162 }
chaviw8b3871a2017-11-01 17:41:01 -07003163 return 0;
3164 }
3165
chaviw8b3871a2017-11-01 17:41:01 -07003166 uint32_t flags = 0;
3167
Garfield Tan8a3083e2018-12-03 13:21:07 -08003168 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003169
3170 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3171 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003172 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003173 layer->pushPendingState();
3174 }
3175
chaviw8b3871a2017-11-01 17:41:01 -07003176 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003177 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003178 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003179 }
chaviw8b3871a2017-11-01 17:41:01 -07003180 }
3181 if (what & layer_state_t::eLayerChanged) {
3182 // NOTE: index needs to be calculated before we update the state
3183 const auto& p = layer->getParent();
3184 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003185 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003186 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003187 mCurrentState.layersSortedByZ.removeAt(idx);
3188 mCurrentState.layersSortedByZ.add(layer);
3189 // we need traversal (state changed)
3190 // AND transaction (list changed)
3191 flags |= eTransactionNeeded|eTraversalNeeded;
3192 }
chaviw8b3871a2017-11-01 17:41:01 -07003193 } else {
3194 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003195 flags |= eTransactionNeeded|eTraversalNeeded;
3196 }
3197 }
chaviw8b3871a2017-11-01 17:41:01 -07003198 }
3199 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003200 // NOTE: index needs to be calculated before we update the state
3201 const auto& p = layer->getParent();
3202 if (p == nullptr) {
3203 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3204 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3205 mCurrentState.layersSortedByZ.removeAt(idx);
3206 mCurrentState.layersSortedByZ.add(layer);
3207 // we need traversal (state changed)
3208 // AND transaction (list changed)
3209 flags |= eTransactionNeeded|eTraversalNeeded;
3210 }
3211 } else {
3212 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3213 flags |= eTransactionNeeded|eTraversalNeeded;
3214 }
chaviw8b3871a2017-11-01 17:41:01 -07003215 }
3216 }
3217 if (what & layer_state_t::eSizeChanged) {
3218 if (layer->setSize(s.w, s.h)) {
3219 flags |= eTraversalNeeded;
3220 }
3221 }
3222 if (what & layer_state_t::eAlphaChanged) {
3223 if (layer->setAlpha(s.alpha))
3224 flags |= eTraversalNeeded;
3225 }
3226 if (what & layer_state_t::eColorChanged) {
3227 if (layer->setColor(s.color))
3228 flags |= eTraversalNeeded;
3229 }
Peiyong Lind3788632018-09-18 16:01:31 -07003230 if (what & layer_state_t::eColorTransformChanged) {
3231 if (layer->setColorTransform(s.colorTransform)) {
3232 flags |= eTraversalNeeded;
3233 }
3234 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003235 if (what & layer_state_t::eBackgroundColorChanged) {
3236 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3237 flags |= eTraversalNeeded;
3238 }
3239 }
chaviw8b3871a2017-11-01 17:41:01 -07003240 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003241 // TODO: b/109894387
3242 //
3243 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3244 // rotation. To see the problem observe that if we have a square parent, and a child
3245 // of the same size, then we rotate the child 45 degrees around it's center, the child
3246 // must now be cropped to a non rectangular 8 sided region.
3247 //
3248 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3249 // private API, and the WindowManager only uses rotation in one case, which is on a top
3250 // level layer in which cropping is not an issue.
3251 //
3252 // However given that abuse of rotation matrices could lead to surfaces extending outside
3253 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3254 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3255 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003256 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003257 flags |= eTraversalNeeded;
3258 }
3259 if (what & layer_state_t::eTransparentRegionChanged) {
3260 if (layer->setTransparentRegionHint(s.transparentRegion))
3261 flags |= eTraversalNeeded;
3262 }
3263 if (what & layer_state_t::eFlagsChanged) {
3264 if (layer->setFlags(s.flags, s.mask))
3265 flags |= eTraversalNeeded;
3266 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003267 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003268 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003269 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003270 if (what & layer_state_t::eCornerRadiusChanged) {
3271 if (layer->setCornerRadius(s.cornerRadius))
3272 flags |= eTraversalNeeded;
3273 }
chaviw8b3871a2017-11-01 17:41:01 -07003274 if (what & layer_state_t::eLayerStackChanged) {
3275 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3276 // We only allow setting layer stacks for top level layers,
3277 // everything else inherits layer stack from its parent.
3278 if (layer->hasParent()) {
3279 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003280 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003281 } else if (idx < 0) {
3282 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003283 "that also does not appear in the top level layer list. Something"
3284 " has gone wrong.",
3285 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003286 } else if (layer->setLayerStack(s.layerStack)) {
3287 mCurrentState.layersSortedByZ.removeAt(idx);
3288 mCurrentState.layersSortedByZ.add(layer);
3289 // we need traversal (state changed)
3290 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003291 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003292 }
3293 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003294 if (what & layer_state_t::eDeferTransaction_legacy) {
3295 if (s.barrierHandle_legacy != nullptr) {
3296 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3297 } else if (s.barrierGbp_legacy != nullptr) {
3298 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003299 if (authenticateSurfaceTextureLocked(gbp)) {
3300 const auto& otherLayer =
3301 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003302 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003303 } else {
3304 ALOGE("Attempt to defer transaction to to an"
3305 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003306 }
3307 }
chaviw8b3871a2017-11-01 17:41:01 -07003308 // We don't trigger a traversal here because if no other state is
3309 // changed, we don't want this to cause any more work
3310 }
chaviw8b3871a2017-11-01 17:41:01 -07003311 if (what & layer_state_t::eReparentChildren) {
3312 if (layer->reparentChildren(s.reparentHandle)) {
3313 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003314 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003315 }
chaviw8b3871a2017-11-01 17:41:01 -07003316 if (what & layer_state_t::eDetachChildren) {
3317 layer->detachChildren();
3318 }
3319 if (what & layer_state_t::eOverrideScalingModeChanged) {
3320 layer->setOverrideScalingMode(s.overrideScalingMode);
3321 // We don't trigger a traversal here because if no other state is
3322 // changed, we don't want this to cause any more work
3323 }
Marissa Wall61c58622018-07-18 10:12:20 -07003324 if (what & layer_state_t::eTransformChanged) {
3325 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3326 }
3327 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3328 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3329 flags |= eTraversalNeeded;
3330 }
3331 if (what & layer_state_t::eCropChanged) {
3332 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3333 }
Marissa Wall861616d2018-10-22 12:52:23 -07003334 if (what & layer_state_t::eFrameChanged) {
3335 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3336 }
Marissa Wall61c58622018-07-18 10:12:20 -07003337 if (what & layer_state_t::eAcquireFenceChanged) {
3338 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3339 }
3340 if (what & layer_state_t::eDataspaceChanged) {
3341 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3342 }
3343 if (what & layer_state_t::eHdrMetadataChanged) {
3344 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3345 }
3346 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3347 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3348 }
3349 if (what & layer_state_t::eApiChanged) {
3350 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3351 }
3352 if (what & layer_state_t::eSidebandStreamChanged) {
3353 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3354 }
Robert Carr720e5062018-07-30 17:45:14 -07003355 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003356 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003357 layer->setInputInfo(s.inputInfo);
3358 flags |= eTraversalNeeded;
3359 } else {
3360 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3361 }
Robert Carr720e5062018-07-30 17:45:14 -07003362 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003363 if (what & layer_state_t::eMetadataChanged) {
3364 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3365 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003366 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3367 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3368 flags |= eTraversalNeeded;
3369 }
3370 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003371 if (what & layer_state_t::eShadowRadiusChanged) {
3372 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3373 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003374 // This has to happen after we reparent children because when we reparent to null we remove
3375 // child layers from current state and remove its relative z. If the children are reparented in
3376 // the same transaction, then we have to make sure we reparent the children first so we do not
3377 // lose its relative z order.
3378 if (what & layer_state_t::eReparent) {
3379 bool hadParent = layer->hasParent();
3380 if (layer->reparent(s.parentHandleForChild)) {
3381 if (!hadParent) {
3382 mCurrentState.layersSortedByZ.remove(layer);
3383 }
3384 flags |= eTransactionNeeded | eTraversalNeeded;
3385 }
3386 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003387 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003388 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3389 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003390 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3391 }
3392 }
Marissa Wall78b72202019-03-15 14:58:34 -07003393 bool bufferChanged = what & layer_state_t::eBufferChanged;
3394 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3395 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003396 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003397 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003398 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3399 if (success) {
3400 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3401 success = ClientCache::getInstance()
3402 .registerErasedRecipient(s.cachedBuffer,
3403 wp<ClientCache::ErasedRecipient>(this));
3404 if (!success) {
3405 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3406 }
3407 }
Marissa Wall78b72202019-03-15 14:58:34 -07003408 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003409 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003410 } else if (bufferChanged) {
3411 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003412 }
Marissa Wall78b72202019-03-15 14:58:34 -07003413 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003414 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003415 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003416 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003417 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003418 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3419 // Do not put anything that updates layer state or modifies flags after
3420 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003421 return flags;
3422}
3423
chaviw273171b2018-12-26 11:46:30 -08003424uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3425 uint32_t flags = 0;
3426 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3427 flags |= eTraversalNeeded;
3428 }
3429
chaviwa911b102019-02-14 10:18:33 -08003430 if (inputWindowCommands.syncInputWindows) {
3431 flags |= eTraversalNeeded;
3432 }
3433
Vishnu Nairec0ab382019-02-13 15:32:56 -08003434 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003435 return flags;
3436}
3437
chaviwfe94a222019-08-21 13:52:59 -07003438status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3439 sp<IBinder>* outHandle) {
3440 if (!mirrorFromHandle) {
3441 return NAME_NOT_FOUND;
3442 }
3443
3444 sp<Layer> mirrorLayer;
3445 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003446 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003447
3448 {
3449 Mutex::Autolock _l(mStateLock);
3450 mirrorFrom = fromHandle(mirrorFromHandle);
3451 if (!mirrorFrom) {
3452 return NAME_NOT_FOUND;
3453 }
3454
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003455 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3456 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003457 if (result != NO_ERROR) {
3458 return result;
3459 }
3460
3461 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3462 }
3463
3464 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3465}
3466
Marissa Wall2d814fb2019-04-09 18:52:57 +00003467status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3468 uint32_t h, PixelFormat format, uint32_t flags,
3469 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003470 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003471 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3472 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003473 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003474 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003475 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003476 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003477 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003478
Robert Carrc0df3122019-04-11 13:18:21 -07003479 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3480 "Expected only one of parentLayer or parentHandle to be non-null. "
3481 "Programmer error?");
3482
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003483 status_t result = NO_ERROR;
3484
3485 sp<Layer> layer;
3486
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003487 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003488
Evan Roskya1f1e152019-01-24 16:17:46 -08003489 bool primaryDisplayOnly = false;
3490
3491 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3492 // TODO b/64227542
3493 if (metadata.has(METADATA_WINDOW_TYPE)) {
3494 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3495 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003496 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003497 primaryDisplayOnly = true;
3498 }
3499 }
3500
Mathias Agopian3165cc22012-08-08 19:42:09 -07003501 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003502 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003503 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3504 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003507 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003508 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003509 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003510 break;
chaviw13fdc492017-06-27 12:40:18 -07003511 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003512 // check if buffer size is set for color layer.
3513 if (w > 0 || h > 0) {
3514 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3515 int(w), int(h));
3516 return BAD_VALUE;
3517 }
3518
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003519 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3520 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003521 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003522 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003523 // check if buffer size is set for container layer.
3524 if (w > 0 || h > 0) {
3525 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3526 int(w), int(h));
3527 return BAD_VALUE;
3528 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003529 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3530 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003531 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003532 default:
3533 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003534 break;
3535 }
3536
Dan Stoza7d89d062015-04-30 13:29:25 -07003537 if (result != NO_ERROR) {
3538 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003539 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003540
Evan Roskya1f1e152019-01-24 16:17:46 -08003541 if (primaryDisplayOnly) {
3542 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003543 }
3544
Robert Carrb89ea9d2018-12-10 13:01:14 -08003545 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003546 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3547 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003548 if (result != NO_ERROR) {
3549 return result;
3550 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003551 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003552
3553 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003554 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555}
3556
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003557std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3558 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003559
3560 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003561 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003562
Dan Stoza436ccf32018-06-21 12:10:12 -07003563 // Grab the state lock since we're accessing mCurrentState
3564 Mutex::Autolock lock(mStateLock);
3565
Cody Northropbc755282017-03-31 12:00:08 -06003566 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003567 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003568 while (matchFound) {
3569 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003570 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003571 if (layer->getName() == uniqueName) {
3572 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003573 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003574 }
3575 });
3576 }
3577
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003578 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003579 return uniqueName;
3580}
3581
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003582status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003583 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003584 LayerMetadata metadata, PixelFormat& format,
3585 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003586 sp<IGraphicBufferProducer>* gbp,
3587 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003588 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003589 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590 case PIXEL_FORMAT_TRANSPARENT:
3591 case PIXEL_FORMAT_TRANSLUCENT:
3592 format = PIXEL_FORMAT_RGBA_8888;
3593 break;
3594 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003595 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003596 break;
3597 }
3598
chaviwb4c6e582019-08-16 14:35:07 -07003599 sp<BufferQueueLayer> layer;
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.textureName = getNewTexture();
3602 {
3603 // Grab the SF state lock during this since it's the only safe way to access
3604 // RenderEngine when creating a BufferLayerConsumer
3605 // TODO: Check if this lock is still needed here
3606 Mutex::Autolock lock(mStateLock);
3607 layer = getFactory().createBufferQueueLayer(args);
3608 }
3609
Marissa Wallfd668622018-05-10 10:21:13 -07003610 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003611 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003612 *handle = layer->getHandle();
3613 *gbp = layer->getProducer();
3614 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003615 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616
Marissa Wallfd668622018-05-10 10:21:13 -07003617 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003618 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003619}
3620
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003621status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003622 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003623 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003624 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003625 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003626 args.displayDevice = getDefaultDisplayDevice();
3627 args.textureName = getNewTexture();
3628 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003629 if (outTransformHint) {
3630 *outTransformHint = layer->getTransformHint();
3631 }
Marissa Wall61c58622018-07-18 10:12:20 -07003632 *handle = layer->getHandle();
3633 *outLayer = layer;
3634
3635 return NO_ERROR;
3636}
3637
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003638status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003639 uint32_t h, uint32_t flags, LayerMetadata metadata,
3640 sp<IBinder>* handle, sp<Layer>* outLayer) {
3641 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003642 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003643 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003645}
3646
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003647status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003648 uint32_t w, uint32_t h, uint32_t flags,
3649 LayerMetadata metadata, sp<IBinder>* handle,
3650 sp<Layer>* outLayer) {
3651 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003652 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003653 *handle = (*outLayer)->getHandle();
3654 return NO_ERROR;
3655}
3656
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003657void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003658 mLayersPendingRemoval.add(layer);
3659 mLayersRemoved = true;
3660 setTransactionFlags(eTransactionNeeded);
3661}
3662
Robert Carr695d5282018-12-18 15:27:58 -08003663void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003664{
Robert Carr2e102c92018-10-23 12:11:15 -07003665 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003666 // If a layer has a parent, we allow it to out-live it's handle
3667 // with the idea that the parent holds a reference and will eventually
3668 // be cleaned up. However no one cleans up the top-level so we do so
3669 // here.
3670 if (layer->getParent() == nullptr) {
3671 mCurrentState.layersSortedByZ.remove(layer);
3672 }
3673 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003674
3675 auto it = mLayersByLocalBinderToken.begin();
3676 while (it != mLayersByLocalBinderToken.end()) {
3677 if (it->second == layer) {
3678 it = mLayersByLocalBinderToken.erase(it);
3679 } else {
3680 it++;
3681 }
3682 }
3683
Robert Carr695d5282018-12-18 15:27:58 -08003684 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003685}
3686
Mathias Agopianb60314a2012-04-10 22:09:54 -07003687// ---------------------------------------------------------------------------
3688
Andy McFadden13a082e2012-08-24 10:16:42 -07003689void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003690 const auto display = getDefaultDisplayDeviceLocked();
3691 if (!display) return;
3692
3693 const sp<IBinder> token = display->getDisplayToken().promote();
3694 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003695
Jesse Hall01e29052013-02-19 16:13:35 -08003696 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003697 Vector<ComposerState> state;
3698 Vector<DisplayState> displays;
3699 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003700 d.what = DisplayState::eDisplayProjectionChanged |
3701 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003702 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003703 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003704 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003705 d.frame.makeInvalid();
3706 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003707 d.width = 0;
3708 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003709 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003710 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3711 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003712
Dominik Laskowskie9774092018-12-11 10:04:24 -08003713 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003714
Dominik Laskowski83b88212018-12-11 13:34:06 -08003715 const nsecs_t vsyncPeriod = getVsyncPeriod();
3716 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003717
Brian Andersond0010582017-03-07 13:20:31 -08003718 // Use phase of 0 since phase is not known.
3719 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003720 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003721 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003722}
3723
3724void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003725 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003726 postMessageAsync(
3727 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003728}
3729
Ady Abraham27c70212019-06-11 10:52:26 -07003730void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3731 if (mHWCVsyncState != enabled) {
3732 getHwComposer().setVsyncEnabled(displayId, enabled);
3733 mHWCVsyncState = enabled;
3734 }
3735}
3736
Dominik Laskowskie9774092018-12-11 10:04:24 -08003737void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003738 if (display->isVirtual()) {
3739 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003740 return;
3741 }
3742
Dominik Laskowski075d3172018-05-24 15:50:06 -07003743 const auto displayId = display->getId();
3744 LOG_ALWAYS_FATAL_IF(!displayId);
3745
Dominik Laskowski34157762018-10-31 13:07:19 -07003746 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003747
3748 int currentMode = display->getPowerMode();
3749 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003750 return;
3751 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003752
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003753 display->setPowerMode(mode);
3754
Lloyd Pique4dccc412018-01-22 17:21:36 -08003755 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003756 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003757 }
3758
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003760 // Turn on the display
Valerie Hauac12ae72019-11-19 14:13:16 -08003761 // TODO: @vhau temp fix only! See b/141111965
3762 mTransactionCompletedThread.clearAllPending();
Dominik Laskowski075d3172018-05-24 15:50:06 -07003763 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003764 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003765 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003766 mScheduler->onScreenAcquired(mAppConnectionHandle);
3767 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003768 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003770 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003771 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003772 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003773
3774 struct sched_param param = {0};
3775 param.sched_priority = 1;
3776 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3777 ALOGW("Couldn't set SCHED_FIFO on display on");
3778 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003779 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003780 // Turn off the display
3781 struct sched_param param = {0};
3782 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3783 ALOGW("Couldn't set SCHED_OTHER on display off");
3784 }
3785
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003786 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003787 mScheduler->disableHardwareVsync(true);
3788 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003789 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003790
Ady Abraham27c70212019-06-11 10:52:26 -07003791 // Make sure HWVsync is disabled before turning off the display
3792 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3793
Dominik Laskowski075d3172018-05-24 15:50:06 -07003794 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003795 mVisibleRegionsDirty = true;
3796 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003797 } else if (mode == HWC_POWER_MODE_DOZE ||
3798 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003799 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003800 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003801 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003802 mScheduler->onScreenAcquired(mAppConnectionHandle);
3803 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003804 }
3805 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3806 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003807 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003808 mScheduler->disableHardwareVsync(true);
3809 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003810 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003811 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003812 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003813 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003814 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003815 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003816
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003817 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003818 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003819 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003820 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003821 }
3822
Dominik Laskowski34157762018-10-31 13:07:19 -07003823 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003824}
3825
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003826void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003827 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003828 const auto display = getDisplayDevice(displayToken);
3829 if (!display) {
3830 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3831 displayToken.get());
3832 } else if (display->isVirtual()) {
3833 ALOGW("Attempt to set power mode %d for virtual display", mode);
3834 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003835 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003836 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003837 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003838}
3839
3840// ---------------------------------------------------------------------------
3841
Dominik Laskowskic2867142019-01-21 11:33:38 -08003842status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3843 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003844 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003845
Mathias Agopianbd115332013-04-18 16:41:04 -07003846 IPCThreadState* ipc = IPCThreadState::self();
3847 const int pid = ipc->getCallingPid();
3848 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003849
Mathias Agopianbd115332013-04-18 16:41:04 -07003850 if ((uid != AID_SHELL) &&
3851 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003852 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3853 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003854 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003855 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003856 // (this would indicate SF is stuck, but we want to be able to
3857 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003858 status_t err = mStateLock.timedLock(s2ns(1));
3859 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003860 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003861 StringAppendF(&result,
3862 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3863 "(no locks held)\n",
3864 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003865 }
3866
Dominik Laskowskic2867142019-01-21 11:33:38 -08003867 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003868 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003869 {"--dispsync"s,
3870 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003871 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003872 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3873 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3874 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3875 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3876 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3877 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003878 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003879 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3880 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003881
Dominik Laskowskic2867142019-01-21 11:33:38 -08003882 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003883
Dominik Laskowski46470112019-08-02 13:13:11 -07003884 const auto it = dumpers.find(flag);
3885 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003886 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003887 } else if (!asProto) {
3888 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003889 }
3890
Mathias Agopian9795c422009-08-26 16:36:26 -07003891 if (locked) {
3892 mStateLock.unlock();
3893 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003894
Dominik Laskowski46470112019-08-02 13:13:11 -07003895 if (it == dumpers.end()) {
3896 const LayersProto layersProto = dumpProtoFromMainThread();
3897 if (asProto) {
3898 result.append(layersProto.SerializeAsString());
3899 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003900 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003901 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3902 result.append(LayerProtoParser::layerTreeToString(layerTree));
3903 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003904 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003905 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003906 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003907 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003908 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 return NO_ERROR;
3910}
3911
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003912status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3913 if (asProto && mTracing.isEnabled()) {
3914 mTracing.writeToFileAsync();
3915 }
3916
3917 return doDump(fd, DumpArgs(), asProto);
3918}
3919
Dominik Laskowskic2867142019-01-21 11:33:38 -08003920void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003921 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003922 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003923}
3924
Dominik Laskowskic2867142019-01-21 11:33:38 -08003925void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003926 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003927
Dominik Laskowskic2867142019-01-21 11:33:38 -08003928 if (args.size() > 1) {
3929 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003930 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003931 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003932 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003933 }
Robert Carr2047fae2016-11-28 14:09:09 -08003934 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003935 } else {
3936 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003937 }
3938}
3939
Dominik Laskowskic2867142019-01-21 11:33:38 -08003940void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003941 const bool clearAll = args.size() < 2;
3942 const auto name = clearAll ? String8() : String8(args[1]);
3943
Robert Carr2047fae2016-11-28 14:09:09 -08003944 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003945 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003946 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003947 }
Robert Carr2047fae2016-11-28 14:09:09 -08003948 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003949
Svetoslavd85084b2014-03-20 10:28:31 -07003950 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003951}
3952
Dominik Laskowskic2867142019-01-21 11:33:38 -08003953void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3954 mTimeStats->parseArgs(asProto, args, result);
3955}
3956
Jamie Gennis6547ff42013-07-16 20:12:42 -07003957// This should only be called from the main thread. Otherwise it would need
3958// the lock and should use mCurrentState rather than mDrawingState.
3959void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003960 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003961 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003962 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003963
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003964 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07003965}
3966
Yiwei Zhang5434a782018-12-05 18:06:32 -08003967void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003968 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003969
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003970 if (isLayerTripleBufferingDisabled())
3971 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003972
Yiwei Zhang5434a782018-12-05 18:06:32 -08003973 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3974 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3975 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3976 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3977 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3978 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003979 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003980}
3981
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003982void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003983 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003984
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003985 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003986 result.append("\n");
3987
Ana Krulec757f63a2019-01-25 10:46:18 -08003988 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003989 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003990 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003991 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003992
Ady Abraham42b3beb2019-07-09 18:09:52 -07003993 StringAppendF(&result, "Allowed Display Configs: ");
Ady Abraham2139f732019-11-13 18:56:40 -08003994 for (auto configId : mAllowedDisplayConfigs) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003995 StringAppendF(&result, "%" PRIu32 " Hz, ",
Ady Abraham2139f732019-11-13 18:56:40 -08003996 static_cast<int32_t>(
3997 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps));
Ady Abraham42b3beb2019-07-09 18:09:52 -07003998 }
3999 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4000 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004001
Ana Krulecc2870422019-01-29 19:00:58 -08004002 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004003}
4004
Yiwei Zhang5434a782018-12-05 18:06:32 -08004005void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4006 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004007 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4008 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004009 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004010 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004011 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004012 }
David Sodman4a36e932017-11-07 14:29:47 -08004013 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004014 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004015 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004016 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4017 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004018}
4019
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004020void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4021 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004022 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4023 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004024 for (const auto& segment : history) {
4025 if (!segment.usedThirdBuffer) {
4026 stats.twoBufferTime += segment.totalTime;
4027 }
4028 if (segment.occupancyAverage < 1.0f) {
4029 stats.doubleBufferedTime += segment.totalTime;
4030 } else if (segment.occupancyAverage < 2.0f) {
4031 stats.tripleBufferedTime += segment.totalTime;
4032 }
4033 ++stats.numSegments;
4034 stats.totalTime += segment.totalTime;
4035 }
4036}
4037
Yiwei Zhang5434a782018-12-05 18:06:32 -08004038void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4039 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004040
4041 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4042 const size_t count = currentLayers.size();
4043 for (size_t i=0 ; i<count ; i++) {
4044 currentLayers[i]->dumpFrameEvents(result);
4045 }
4046}
4047
Yiwei Zhang5434a782018-12-05 18:06:32 -08004048void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004049 result.append("Buffering stats:\n");
4050 result.append(" [Layer name] <Active time> <Two buffer> "
4051 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004052 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004053 typedef std::tuple<std::string, float, float, float> BufferTuple;
4054 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004055 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004056 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004057 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004058 if (stats.numSegments == 0) {
4059 continue;
4060 }
4061 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4062 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4063 stats.totalTime;
4064 float doubleBufferRatio = static_cast<float>(
4065 stats.doubleBufferedTime) / stats.totalTime;
4066 float tripleBufferRatio = static_cast<float>(
4067 stats.tripleBufferedTime) / stats.totalTime;
4068 sorted.insert({activeTime, {name, twoBufferRatio,
4069 doubleBufferRatio, tripleBufferRatio}});
4070 }
4071 for (const auto& sortedPair : sorted) {
4072 float activeTime = sortedPair.first;
4073 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004074 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4075 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004076 }
4077 result.append("\n");
4078}
4079
Yiwei Zhang5434a782018-12-05 18:06:32 -08004080void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004081 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004082 const auto displayId = display->getId();
4083 if (!displayId) {
4084 continue;
4085 }
4086 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004087 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004088 continue;
4089 }
4090
Yiwei Zhang5434a782018-12-05 18:06:32 -08004091 StringAppendF(&result,
4092 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4093 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004094 uint8_t port;
4095 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004096 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004097 result.append("no identification data\n");
4098 continue;
4099 }
4100
4101 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004102 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004103 continue;
4104 }
4105
4106 const auto edid = parseEdid(data);
4107 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004108 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004109 continue;
4110 }
4111
Yiwei Zhang5434a782018-12-05 18:06:32 -08004112 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004113 result.append(edid->displayName.data(), edid->displayName.length());
4114 result.append("\"\n");
4115 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004116}
4117
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004118void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4119 std::string& result) const {
4120 hwc2_display_t hwcDisplayId;
4121 uint8_t port;
4122 DisplayIdentificationData data;
4123
4124 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4125 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4126 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4127 }
4128}
4129
Yiwei Zhang5434a782018-12-05 18:06:32 -08004130void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004131 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004132 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4133 StringAppendF(&result, "DisplayColorSetting: %s\n",
4134 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004135
4136 // TODO: print out if wide-color mode is active or not
4137
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004138 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004139 const auto displayId = display->getId();
4140 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004141 continue;
4142 }
4143
Yiwei Zhang5434a782018-12-05 18:06:32 -08004144 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004145 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004146 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004147 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004148 }
4149
Lloyd Pique32cbe282018-10-19 13:09:22 -07004150 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004151 StringAppendF(&result, " Current color mode: %s (%d)\n",
4152 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004153 }
4154 result.append("\n");
4155}
4156
Vishnu Nair8406fd72019-07-30 11:29:31 -07004157LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004158 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004159 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004160 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004161 layer->writeToProtoDrawingState(layerProto, traceFlags);
4162 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004163 });
4164
4165 return layersProto;
4166}
4167
Vishnu Nair0f085c62019-08-30 08:49:12 -07004168void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4169 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4170 // it.
4171 LayerProto* rootProto = layersProto.add_layers();
4172 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4173 rootProto->set_id(offscreenRootLayerId);
4174 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004175 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004176
4177 for (Layer* offscreenLayer : mOffscreenLayers) {
4178 // Add layer as child of the fake root
4179 rootProto->add_children(offscreenLayer->sequence);
4180
4181 // Add layer
4182 LayerProto* layerProto = layersProto.add_layers();
4183 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4184 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4185 traceFlags);
4186 layerProto->set_parent(offscreenRootLayerId);
4187
4188 // Add children
4189 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4190 if (layer == offscreenLayer) {
4191 return;
4192 }
4193 LayerProto* childProto = layersProto.add_layers();
4194 layer->writeToProtoDrawingState(childProto, traceFlags);
4195 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4196 });
4197 }
4198}
4199
Vishnu Nair8406fd72019-07-30 11:29:31 -07004200LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4201 LayersProto layersProto;
4202 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4203 return layersProto;
4204}
4205
Vishnu Nair0f085c62019-08-30 08:49:12 -07004206void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4207 result.append("Offscreen Layers:\n");
4208 postMessageSync(new LambdaMessage([&]() {
4209 for (Layer* offscreenLayer : mOffscreenLayers) {
4210 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4211 layer->dumpCallingUidPid(result);
4212 });
4213 }
4214 }));
4215}
4216
Dominik Laskowskic2867142019-01-21 11:33:38 -08004217void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4218 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004219 Colorizer colorizer(colorize);
4220
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004221 // figure out if we're stuck somewhere
4222 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004223 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004224 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4225
4226 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004227 * Dump library configuration.
4228 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004229
4230 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004231 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004232 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004233 appendSfConfigString(result);
4234 appendUiConfigString(result);
4235 appendGuiConfigString(result);
4236 result.append("\n");
4237
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004238 result.append("\nDisplay identification data:\n");
4239 dumpDisplayIdentificationData(result);
4240
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004241 result.append("\nWide-Color information:\n");
4242 dumpWideColorInfo(result);
4243
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004244 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004245 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004246 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004247 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004248 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004249
Andy McFadden41d67d72014-04-25 16:58:34 -07004250 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004251 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004252 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004253 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004254 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004255
Dan Stozab90cf072015-03-05 11:05:59 -08004256 dumpStaticScreenStats(result);
4257 result.append("\n");
4258
Alec Mouri40189b02019-03-05 15:07:54 -08004259 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4260 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4261 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004262
Dan Stozae77c7662016-05-13 11:37:28 -07004263 dumpBufferingStats(result);
4264
Andy McFadden4803b742012-09-24 19:07:20 -07004265 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266 * Dump the visible layer list
4267 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004269 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004270 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4271 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004272 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004273
Chia-I Wu2f884132018-09-13 15:17:58 -07004274 {
Lloyd Pique207def92019-02-28 16:09:52 -08004275 StringAppendF(&result, "Composition layers\n");
4276 mDrawingState.traverseInZOrder([&](Layer* layer) {
4277 auto compositionLayer = layer->getCompositionLayer();
4278 if (compositionLayer) compositionLayer->dump(result);
4279 });
4280 }
4281
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004282 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004283 * Dump Display state
4284 */
4285
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004286 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004287 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004289 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004290 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004291 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004292 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004293
4294 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004295 * Dump CompositionEngine state
4296 */
4297
4298 mCompositionEngine->dump(result);
4299
4300 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004301 * Dump SurfaceFlinger global state
4302 */
4303
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004304 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004305 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004306 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004307
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004308 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004309
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004310 DebugEGLImageTracker::getInstance()->dump(result);
4311
Dominik Laskowski075d3172018-05-24 15:50:06 -07004312 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004313 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4314 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4316 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004317 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004318 StringAppendF(&result,
4319 " transaction-flags : %08x\n"
4320 " gpu_to_cpu_unsupported : %d\n",
4321 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004322
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004323 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004324 displayId && getHwComposer().isConnected(*displayId)) {
4325 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004326 StringAppendF(&result,
4327 " refresh-rate : %f fps\n"
4328 " x-dpi : %f\n"
4329 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004330 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4331 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004332 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
Yiwei Zhang5434a782018-12-05 18:06:32 -08004334 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335
Dan Stozae22aec72016-08-01 13:20:59 -07004336 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004337 * Tracing state
4338 */
4339 mTracing.dump(result);
4340 result.append("\n");
4341
4342 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004343 * HWC layer minidump
4344 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004345 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004346 const auto displayId = display->getId();
4347 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004348 continue;
4349 }
4350
Yiwei Zhang5434a782018-12-05 18:06:32 -08004351 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004352 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004353 const sp<DisplayDevice> displayDevice = display;
4354 mCurrentState.traverseInZOrder(
4355 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004356 result.append("\n");
4357 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004358
4359 /*
4360 * Dump HWComposer state
4361 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004362 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004363 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004364 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004365 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004366 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004367 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004368
4369 /*
4370 * Dump gralloc state
4371 */
4372 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4373 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004374
4375 /*
4376 * Dump VrFlinger state if in use.
4377 */
4378 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4379 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004380 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004381 result.append("\n");
4382 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004383
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004384 result.append(mTimeStats->miniDump());
4385 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004386}
4387
Chia-I Wu28f320b2018-05-03 11:02:56 -07004388void SurfaceFlinger::updateColorMatrixLocked() {
4389 mat4 colorMatrix;
4390 if (mGlobalSaturationFactor != 1.0f) {
4391 // Rec.709 luma coefficients
4392 float3 luminance{0.213f, 0.715f, 0.072f};
4393 luminance *= 1.0f - mGlobalSaturationFactor;
4394 mat4 saturationMatrix = mat4(
4395 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4396 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4397 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4398 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4399 );
4400 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4401 } else {
4402 colorMatrix = mClientColorMatrix * mDaltonizer();
4403 }
4404
4405 if (mCurrentState.colorMatrix != colorMatrix) {
4406 mCurrentState.colorMatrix = colorMatrix;
4407 mCurrentState.colorMatrixChanged = true;
4408 setTransactionFlags(eTransactionNeeded);
4409 }
4410}
4411
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004412status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004413#pragma clang diagnostic push
4414#pragma clang diagnostic error "-Wswitch-enum"
4415 switch (static_cast<ISurfaceComposerTag>(code)) {
4416 // These methods should at minimum make sure that the client requested
4417 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004418 case BOOT_FINISHED:
4419 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004420 case CREATE_DISPLAY:
4421 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004422 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004423 case GET_ANIMATION_FRAME_STATS:
4424 case GET_HDR_CAPABILITIES:
4425 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004426 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004427 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004428 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004429 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004430 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004431 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004432 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004433 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004434 case NOTIFY_POWER_HINT:
4435 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004436 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4437 IPCThreadState* ipc = IPCThreadState::self();
4438 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4439 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004440 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004441 }
Robert Carr1db73f62016-12-21 12:58:51 -08004442 return OK;
4443 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004444 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004445 IPCThreadState* ipc = IPCThreadState::self();
4446 const int pid = ipc->getCallingPid();
4447 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004448 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4449 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004450 return PERMISSION_DENIED;
4451 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004452 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004453 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004454 // Used by apps to hook Choreographer to SurfaceFlinger.
4455 case CREATE_DISPLAY_EVENT_CONNECTION:
4456 // The following calls are currently used by clients that do not
4457 // request necessary permissions. However, they do not expose any secret
4458 // information, so it is OK to pass them.
4459 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004460 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004461 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004462 case GET_PHYSICAL_DISPLAY_IDS:
4463 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004464 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004465 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004466 case GET_DISPLAY_CONFIGS:
4467 case GET_DISPLAY_STATS:
4468 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4469 // Calling setTransactionState is safe, because you need to have been
4470 // granted a reference to Client* and Handle* to do anything with it.
4471 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004472 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004473 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004474 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004475 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004476 case IS_WIDE_COLOR_DISPLAY:
4477 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4478 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004479 return OK;
4480 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004481 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004482 case CAPTURE_SCREEN:
4483 case ADD_REGION_SAMPLING_LISTENER:
4484 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004485 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004486 IPCThreadState* ipc = IPCThreadState::self();
4487 const int pid = ipc->getCallingPid();
4488 const int uid = ipc->getCallingUid();
4489 if ((uid != AID_GRAPHICS) &&
4490 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4491 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4492 return PERMISSION_DENIED;
4493 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004494 return OK;
4495 }
4496 // The following codes are deprecated and should never be allowed to access SF.
4497 case CONNECT_DISPLAY_UNUSED:
4498 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4499 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4500 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004501 }
chaviw93df2ea2019-04-30 16:45:12 -07004502 case CAPTURE_SCREEN_BY_ID: {
4503 IPCThreadState* ipc = IPCThreadState::self();
4504 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004505 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004506 return OK;
4507 }
4508 return PERMISSION_DENIED;
4509 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004510 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004511
4512 // These codes are used for the IBinder protocol to either interrogate the recipient
4513 // side of the transaction for its canonical interface descriptor or to dump its state.
4514 // We let them pass by default.
4515 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4516 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4517 code == IBinder::SYSPROPS_TRANSACTION) {
4518 return OK;
4519 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004520 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004521 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004522 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004523 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4524 return OK;
4525 }
4526 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4527 return PERMISSION_DENIED;
4528#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004529}
4530
Ana Krulec13be8ad2018-08-21 02:43:56 +00004531status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4532 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004533 status_t credentialCheck = CheckTransactCodeCredentials(code);
4534 if (credentialCheck != OK) {
4535 return credentialCheck;
4536 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004537
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004538 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4539 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004540 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004541 IPCThreadState* ipc = IPCThreadState::self();
4542 const int uid = ipc->getCallingUid();
4543 if (CC_UNLIKELY(uid != AID_SYSTEM
4544 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004545 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004546 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004547 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004548 return PERMISSION_DENIED;
4549 }
4550 int n;
4551 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004552 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004553 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004554 return NO_ERROR;
4555 case 1002: // SHOW_UPDATES
4556 n = data.readInt32();
4557 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004558 invalidateHwcGeometry();
4559 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004560 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004561 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004562 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004563 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004565 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004566 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004567 setTransactionFlags(
4568 eTransactionNeeded|
4569 eDisplayTransactionNeeded|
4570 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004571 return NO_ERROR;
4572 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004573 case 1006:{ // send empty update
4574 signalRefresh();
4575 return NO_ERROR;
4576 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004577 case 1008: // toggle use of hw composer
4578 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004579 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004580 invalidateHwcGeometry();
4581 repaintEverything();
4582 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004583 case 1009: // toggle use of transform hint
4584 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004585 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004586 invalidateHwcGeometry();
4587 repaintEverything();
4588 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004589 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004590 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004591 reply->writeInt32(0);
4592 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004593 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004594 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004595 return NO_ERROR;
4596 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004597 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004598 if (!display) {
4599 return NAME_NOT_FOUND;
4600 }
4601
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004602 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004603 return NO_ERROR;
4604 }
4605 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004606 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004607 // daltonize
4608 n = data.readInt32();
4609 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004610 case 1:
4611 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4612 break;
4613 case 2:
4614 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4615 break;
4616 case 3:
4617 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4618 break;
4619 default:
4620 mDaltonizer.setType(ColorBlindnessType::None);
4621 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004622 }
4623 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004624 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004625 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004626 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004627 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004628
4629 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004630 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004631 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004632 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004633 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004634 // apply a color matrix
4635 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004636 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004637 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004638 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004639 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004640 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004641 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004642 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004643 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004644 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004645 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004646
4647 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4648 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004649 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004650 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4651 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4652 }
4653
Chia-I Wu28f320b2018-05-03 11:02:56 -07004654 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004655 return NO_ERROR;
4656 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004657 case 1016: { // Unused.
4658 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004659 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004660 case 1017: {
4661 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004662 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004663 return NO_ERROR;
4664 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004665 case 1018: { // Modify Choreographer's phase offset
4666 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004667 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004668 return NO_ERROR;
4669 }
4670 case 1019: { // Modify SurfaceFlinger's phase offset
4671 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004672 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004673 return NO_ERROR;
4674 }
Irvel468051e2016-06-13 16:44:44 -07004675 case 1020: { // Layer updates interceptor
4676 n = data.readInt32();
4677 if (n) {
4678 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004679 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004680 }
4681 else{
4682 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004683 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004684 }
4685 return NO_ERROR;
4686 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004687 case 1021: { // Disable HWC virtual displays
4688 n = data.readInt32();
4689 mUseHwcVirtualDisplays = !n;
4690 return NO_ERROR;
4691 }
Romain Guy0147a172017-06-01 13:53:56 -07004692 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004693 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004694 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004695
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004697 return NO_ERROR;
4698 }
Romain Guy54f154a2017-10-24 21:40:32 +01004699 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004700 int32_t colorMode;
4701
Chia-I Wu0d711262018-05-21 15:19:35 -07004702 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004703 if (data.readInt32(&colorMode) == NO_ERROR) {
4704 mForceColorMode = static_cast<ColorMode>(colorMode);
4705 }
Romain Guy54f154a2017-10-24 21:40:32 +01004706 invalidateHwcGeometry();
4707 repaintEverything();
4708 return NO_ERROR;
4709 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004710 // Deprecate, use 1030 to check whether the device is color managed.
4711 case 1024: {
4712 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004713 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004714 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004715 n = data.readInt32();
4716 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004717 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004718 Mutex::Autolock lock(mStateLock);
4719 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004720 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004721 reply->writeInt32(NO_ERROR);
4722 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004723 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004724 bool writeFile = false;
4725 {
4726 Mutex::Autolock lock(mStateLock);
4727 mTracingEnabledChanged = true;
4728 writeFile = mTracing.disable();
4729 }
4730
4731 if (writeFile) {
4732 reply->writeInt32(mTracing.writeToFile());
4733 } else {
4734 reply->writeInt32(NO_ERROR);
4735 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004736 }
4737 return NO_ERROR;
4738 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004739 case 1026: { // Get layer tracing status
4740 reply->writeBool(mTracing.isEnabled());
4741 return NO_ERROR;
4742 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004743 // Is a DisplayColorSetting supported?
4744 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004745 const auto display = getDefaultDisplayDevice();
4746 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004747 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004748 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004749
4750 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4751 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004752 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004753 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004754 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004755 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004756 reply->writeBool(true);
4757 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004758 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004759 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004760 break;
4761 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004762 reply->writeBool(
4763 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004764 break;
4765 }
4766 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004767 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004768 // Is VrFlinger active?
4769 case 1028: {
4770 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004771 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004772 return NO_ERROR;
4773 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004774 // Set buffer size for SF tracing (value in KB)
4775 case 1029: {
4776 n = data.readInt32();
4777 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4778 ALOGW("Invalid buffer size: %d KB", n);
4779 reply->writeInt32(BAD_VALUE);
4780 return BAD_VALUE;
4781 }
4782
4783 ALOGD("Updating trace buffer to %d KB", n);
4784 mTracing.setBufferSize(n * 1024);
4785 reply->writeInt32(NO_ERROR);
4786 return NO_ERROR;
4787 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004788 // Is device color managed?
4789 case 1030: {
4790 reply->writeBool(useColorManagement);
4791 return NO_ERROR;
4792 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004793 // Override default composition data space
4794 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4795 // && adb shell stop zygote && adb shell start zygote
4796 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4797 // adb shell stop zygote && adb shell start zygote
4798 case 1031: {
4799 Mutex::Autolock _l(mStateLock);
4800 n = data.readInt32();
4801 if (n) {
4802 n = data.readInt32();
4803 if (n) {
4804 Dataspace dataspace = static_cast<Dataspace>(n);
4805 if (!validateCompositionDataspace(dataspace)) {
4806 return BAD_VALUE;
4807 }
4808 mDefaultCompositionDataspace = dataspace;
4809 }
4810 n = data.readInt32();
4811 if (n) {
4812 Dataspace dataspace = static_cast<Dataspace>(n);
4813 if (!validateCompositionDataspace(dataspace)) {
4814 return BAD_VALUE;
4815 }
4816 mWideColorGamutCompositionDataspace = dataspace;
4817 }
4818 } else {
4819 // restore composition data space.
4820 mDefaultCompositionDataspace = defaultCompositionDataspace;
4821 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4822 }
4823 return NO_ERROR;
4824 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004825 // Set trace flags
4826 case 1033: {
4827 n = data.readUint32();
4828 ALOGD("Updating trace flags to 0x%x", n);
4829 mTracing.setTraceFlags(n);
4830 reply->writeInt32(NO_ERROR);
4831 return NO_ERROR;
4832 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004833 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004834 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004835 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004836 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004837 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4838 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004839 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004840 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004841 } else {
4842 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004843 }
4844 return NO_ERROR;
4845 }
Ady Abraham34392f72019-04-10 11:29:27 -07004846 case 1035: {
4847 n = data.readInt32();
4848 mDebugDisplayConfigSetByBackdoor = false;
4849 if (n >= 0) {
4850 const auto displayToken = getInternalDisplayToken();
4851 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4852 if (result != NO_ERROR) {
4853 return result;
4854 }
4855 mDebugDisplayConfigSetByBackdoor = true;
4856 }
4857 return NO_ERROR;
4858 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004859 }
4860 }
4861 return err;
4862}
4863
Steven Thomas6d8110b2017-08-31 18:24:21 -07004864void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004865 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004866 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004867}
4868
Ana Krulec7d1d6832018-12-27 11:10:09 -08004869void SurfaceFlinger::repaintEverythingForHWC() {
4870 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004871 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004872}
4873
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004874// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4875class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004876public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004877 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4878 ~WindowDisconnector() {
4879 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004880 }
4881
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004882private:
4883 ANativeWindow* mWindow;
4884 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004885};
4886
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004887status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004888 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4889 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004890 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004891 uint32_t reqWidth, uint32_t reqHeight,
4892 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004893 ISurfaceComposer::Rotation rotation,
4894 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004895 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004896
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004897 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004898
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004899 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4900
Chia-I Wu20261cb2018-08-23 12:55:44 -07004901 sp<DisplayDevice> display;
4902 {
4903 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004904
Chia-I Wu20261cb2018-08-23 12:55:44 -07004905 display = getDisplayDeviceLocked(displayToken);
4906 if (!display) return BAD_VALUE;
4907
Chia-I Wucb023152018-08-28 12:57:23 -07004908 // set the requested width/height to the logical display viewport size
4909 // by default
4910 if (reqWidth == 0 || reqHeight == 0) {
4911 reqWidth = uint32_t(display->getViewport().width());
4912 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004913 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004914 }
4915
Peiyong Lin0e003c92018-09-17 11:09:51 -07004916 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004917 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004918
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004919 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4920 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004921 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004922 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004923}
4924
chaviw93df2ea2019-04-30 16:45:12 -07004925static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4926 switch (colorMode) {
4927 case ColorMode::DISPLAY_P3:
4928 case ColorMode::BT2100_PQ:
4929 case ColorMode::BT2100_HLG:
4930 case ColorMode::DISPLAY_BT2020:
4931 return Dataspace::DISPLAY_P3;
4932 default:
4933 return Dataspace::V0_SRGB;
4934 }
4935}
4936
4937const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4938 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4939 if (displayToken) {
4940 return getDisplayDeviceLocked(displayToken);
4941 }
4942 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4943 // may not have a displayId.
4944 for (const auto& [token, display] : mDisplays) {
4945 if (display->getLayerStack() == displayOrLayerStack) {
4946 return display;
4947 }
4948 }
4949 return nullptr;
4950}
4951
4952status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4953 sp<GraphicBuffer>* outBuffer) {
4954 sp<DisplayDevice> display;
4955 uint32_t width;
4956 uint32_t height;
4957 ui::Transform::orientation_flags captureOrientation;
4958 {
4959 Mutex::Autolock _l(mStateLock);
4960 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4961 if (!display) {
4962 return BAD_VALUE;
4963 }
4964
4965 width = uint32_t(display->getViewport().width());
4966 height = uint32_t(display->getViewport().height());
4967
4968 captureOrientation = fromSurfaceComposerRotation(
4969 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004970 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4971 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4972 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4973 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4974 }
chaviw93df2ea2019-04-30 16:45:12 -07004975 *outDataspace =
4976 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4977 }
4978
4979 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4980 false /* captureSecureLayers */);
4981
4982 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4983 std::placeholders::_1);
4984 bool ignored = false;
4985 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4986 false /* useIdentityTransform */,
4987 ignored /* outCapturedSecureLayers */);
4988}
4989
Robert Carr866455f2019-04-02 16:28:26 -07004990status_t SurfaceFlinger::captureLayers(
4991 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4992 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4993 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4994 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004995 ATRACE_CALL();
4996
4997 class LayerRenderArea : public RenderArea {
4998 public:
Robert Carr578038f2018-03-09 12:25:24 -08004999 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005000 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5001 bool childrenOnly)
5002 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005003 mLayer(layer),
5004 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005005 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005006 mFlinger(flinger),
5007 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005008 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005009 Rect getBounds() const override {
5010 const Layer::State& layerState(mLayer->getDrawingState());
5011 return mLayer->getBufferSize(layerState);
5012 }
Marissa Wall61c58622018-07-18 10:12:20 -07005013 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005014 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005015 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005016 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005017 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005018 }
chaviwa76b2712017-09-20 12:02:26 -07005019 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005020 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005021 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005022 Rect getSourceCrop() const override {
5023 if (mCrop.isEmpty()) {
5024 return getBounds();
5025 } else {
5026 return mCrop;
5027 }
5028 }
Robert Carr578038f2018-03-09 12:25:24 -08005029 class ReparentForDrawing {
5030 public:
5031 const sp<Layer>& oldParent;
5032 const sp<Layer>& newParent;
5033
Vishnu Nair4351ad52019-02-11 14:13:02 -08005034 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5035 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005036 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005037 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005038 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5039 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005040 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005041 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005042 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005043 };
5044
5045 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005046 const Rect sourceCrop = getSourceCrop();
5047 // no need to check rotation because there is none
5048 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5049 sourceCrop.height() != getReqHeight();
5050
Robert Carr578038f2018-03-09 12:25:24 -08005051 if (!mChildrenOnly) {
5052 mTransform = mLayer->getTransform().inverse();
5053 drawLayers();
5054 } else {
5055 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005056 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5057 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005058 // In the "childrenOnly" case we reparent the children to a screenshot
5059 // layer which has no properties set and which does not draw.
5060 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005061 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5062 "Screenshot Parent"s, w, h, 0,
5063 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005064
Vishnu Nair4351ad52019-02-11 14:13:02 -08005065 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005066 drawLayers();
5067 }
5068 }
chaviwa76b2712017-09-20 12:02:26 -07005069
chaviwa76b2712017-09-20 12:02:26 -07005070 private:
chaviw7206d492017-11-10 16:16:12 -08005071 const sp<Layer> mLayer;
5072 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005073
Peiyong Linefefaac2018-08-17 12:27:51 -07005074 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005075 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005076
5077 SurfaceFlinger* mFlinger;
5078 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005079 };
5080
Robert Carrc0df3122019-04-11 13:18:21 -07005081 int reqWidth = 0;
5082 int reqHeight = 0;
5083 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005084 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005085 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005086
Robert Carrc0df3122019-04-11 13:18:21 -07005087 {
5088 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005089
Robert Carrc0df3122019-04-11 13:18:21 -07005090 parent = fromHandle(layerHandleBinder);
5091 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5092 ALOGE("captureLayers called with an invalid or removed parent");
5093 return NAME_NOT_FOUND;
5094 }
5095
5096 const int uid = IPCThreadState::self()->getCallingUid();
5097 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5098 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5099 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5100 return PERMISSION_DENIED;
5101 }
5102
5103 if (sourceCrop.width() <= 0) {
5104 crop.left = 0;
5105 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5106 }
5107
5108 if (sourceCrop.height() <= 0) {
5109 crop.top = 0;
5110 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5111 }
5112 reqWidth = crop.width() * frameScale;
5113 reqHeight = crop.height() * frameScale;
5114
5115 for (const auto& handle : excludeHandles) {
5116 sp<Layer> excludeLayer = fromHandle(handle);
5117 if (excludeLayer != nullptr) {
5118 excludeLayers.emplace(excludeLayer);
5119 } else {
5120 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5121 return NAME_NOT_FOUND;
5122 }
5123 }
5124 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005125
Chia-I Wu20261cb2018-08-23 12:55:44 -07005126 // really small crop or frameScale
5127 if (reqWidth <= 0) {
5128 reqWidth = 1;
5129 }
5130 if (reqHeight <= 0) {
5131 reqHeight = 1;
5132 }
5133
Robert Carr866455f2019-04-02 16:28:26 -07005134 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5135 auto traverseLayers = [parent, childrenOnly,
5136 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005137 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5138 if (!layer->isVisible()) {
5139 return;
Robert Carr578038f2018-03-09 12:25:24 -08005140 } else if (childrenOnly && layer == parent.get()) {
5141 return;
chaviwa76b2712017-09-20 12:02:26 -07005142 }
Robert Carr866455f2019-04-02 16:28:26 -07005143
5144 sp<Layer> p = layer;
5145 while (p != nullptr) {
5146 if (excludeLayers.count(p) != 0) {
5147 return;
5148 }
5149 p = p->getParent();
5150 }
5151
chaviwa76b2712017-09-20 12:02:26 -07005152 visitor(layer);
5153 });
5154 };
Robert Carr108b2c72019-04-02 16:32:58 -07005155
5156 bool outCapturedSecureLayers = false;
5157 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5158 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005159}
5160
5161status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5162 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005163 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005164 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005165 bool useIdentityTransform,
5166 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005167 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005168
Peiyong Lin0e003c92018-09-17 11:09:51 -07005169 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005170 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5171 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005172 *outBuffer =
5173 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5174 static_cast<android_pixel_format>(reqPixelFormat), 1,
5175 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005176
Robert Carr108b2c72019-04-02 16:32:58 -07005177 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5178 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005179}
5180
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005181status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5182 TraverseLayersFunction traverseLayers,
5183 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005184 bool useIdentityTransform,
5185 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005186 // This mutex protects syncFd and captureResult for communication of the return values from the
5187 // main thread back to this Binder thread
5188 std::mutex captureMutex;
5189 std::condition_variable captureCondition;
5190 std::unique_lock<std::mutex> captureLock(captureMutex);
5191 int syncFd = -1;
5192 std::optional<status_t> captureResult;
5193
Robert Carr03480e22018-01-04 16:02:06 -08005194 const int uid = IPCThreadState::self()->getCallingUid();
5195 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5196
Dominik Laskowski8c001672018-05-30 16:52:06 -07005197 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005198 // If there is a refresh pending, bug out early and tell the binder thread to try again
5199 // after the refresh.
5200 if (mRefreshPending) {
5201 ATRACE_NAME("Skipping screenshot for now");
5202 std::unique_lock<std::mutex> captureLock(captureMutex);
5203 captureResult = std::make_optional<status_t>(EAGAIN);
5204 captureCondition.notify_one();
5205 return;
5206 }
5207
5208 status_t result = NO_ERROR;
5209 int fd = -1;
5210 {
5211 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005212 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005213 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005214 useIdentityTransform, forSystem, &fd,
5215 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005216 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005217 }
5218
5219 {
5220 std::unique_lock<std::mutex> captureLock(captureMutex);
5221 syncFd = fd;
5222 captureResult = std::make_optional<status_t>(result);
5223 captureCondition.notify_one();
5224 }
5225 });
5226
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005227 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005228 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005229 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005230 while (*captureResult == EAGAIN) {
5231 captureResult.reset();
5232 result = postMessageAsync(message);
5233 if (result != NO_ERROR) {
5234 return result;
5235 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005236 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005237 }
5238 result = *captureResult;
5239 }
5240
5241 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005242 sync_wait(syncFd, -1);
5243 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005245
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005246 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005247}
5248
chaviwa76b2712017-09-20 12:02:26 -07005249void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005250 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005251 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5252 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005253 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005254
chaviwa76b2712017-09-20 12:02:26 -07005255 const auto reqWidth = renderArea.getReqWidth();
5256 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005257 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005258 const auto transform = renderArea.getTransform();
5259 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005260
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005261 renderengine::DisplaySettings clientCompositionDisplay;
5262 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005263
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005264 // assume that bounds are never offset, and that they are the same as the
5265 // buffer bounds.
5266 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005267 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005268 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005269
5270 // Now take into account the rotation flag. We append a transform that
5271 // rotates the layer stack about the origin, then translate by buffer
5272 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005273 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005274 int displacementX = 0;
5275 int displacementY = 0;
5276 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5277 switch (rotation) {
5278 case ui::Transform::ROT_90:
5279 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005280 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005281 break;
5282 case ui::Transform::ROT_180:
5283 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005284 displacementY = renderArea.getBounds().getWidth();
5285 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005286 break;
5287 case ui::Transform::ROT_270:
5288 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005289 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005290 break;
5291 default:
5292 break;
5293 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005294
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005295 // We need to transform the clipping window into the right spot.
5296 // First, rotate the clipping rectangle by the rotation hint to get the
5297 // right orientation
5298 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5299 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5300 const vec4 rotClipTL = rotMatrix * clipTL;
5301 const vec4 rotClipBR = rotMatrix * clipBR;
5302 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5303 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5304 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5305 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5306
5307 // Now reposition the clipping rectangle with the displacement vector
5308 // computed above.
5309 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005310 clientCompositionDisplay.clip =
5311 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5312 newClipRight + displacementX, newClipBottom + displacementY);
5313
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005314 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005315 clientCompositionDisplay.globalTransform =
5316 clipTransform * clientCompositionDisplay.globalTransform;
5317
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005318 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5319 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005320
chaviw50da5042018-04-09 13:49:37 -07005321 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005322
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005323 renderengine::LayerSettings fillLayer;
5324 fillLayer.source.buffer.buffer = nullptr;
5325 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5326 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5327 fillLayer.alpha = half(alpha);
5328 clientCompositionLayers.push_back(fillLayer);
5329
5330 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005331 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005332 const bool supportProtectedContent = false;
5333 Region clip(renderArea.getBounds());
5334 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5335 clip,
5336 useIdentityTransform,
5337 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5338 renderArea.isSecure(),
5339 supportProtectedContent,
5340 clearRegion,
5341 };
5342 auto result = layer->prepareClientComposition(targetSettings);
5343 if (result) {
5344 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005345 }
chaviwa76b2712017-09-20 12:02:26 -07005346 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005347
5348 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005349 // Use an empty fence for the buffer fence, since we just created the buffer so
5350 // there is no need for synchronization with the GPU.
5351 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005352 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005353 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005354 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005355 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005356
5357 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005358}
5359
chaviwa76b2712017-09-20 12:02:26 -07005360status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5361 TraverseLayersFunction traverseLayers,
5362 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005363 bool useIdentityTransform, bool forSystem,
5364 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005365 ATRACE_CALL();
5366
chaviwa76b2712017-09-20 12:02:26 -07005367 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005368 outCapturedSecureLayers =
5369 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005370 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005371
Robert Carr03480e22018-01-04 16:02:06 -08005372 // We allow the system server to take screenshots of secure layers for
5373 // use in situations like the Screen-rotation animation and place
5374 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005375 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005376 ALOGW("FB is protected: PERMISSION_DENIED");
5377 return PERMISSION_DENIED;
5378 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005379 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005380 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005381}
5382
chaviw95ef3c42019-02-14 10:55:09 -08005383void SurfaceFlinger::setInputWindowsFinished() {
5384 Mutex::Autolock _l(mStateLock);
5385
5386 mPendingSyncInputWindows = false;
5387 mTransactionCV.broadcast();
5388}
chaviw5f21a5e2019-02-14 10:00:34 -08005389
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005390// ---------------------------------------------------------------------------
5391
Dan Stoza412903f2017-04-27 13:42:17 -07005392void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5393 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005394}
5395
Dan Stoza412903f2017-04-27 13:42:17 -07005396void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5397 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005398}
5399
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005400void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005401 const LayerVector::Visitor& visitor) {
5402 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005403 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005404 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005405 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005406 continue;
5407 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005408 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005409 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005410 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005411 return;
5412 }
chaviwa76b2712017-09-20 12:02:26 -07005413 if (!layer->isVisible()) {
5414 return;
5415 }
5416 visitor(layer);
5417 });
5418 }
5419}
5420
Dominik Laskowski22488f62019-03-28 09:53:04 -07005421void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5422 const std::vector<int32_t>& allowedConfigs) {
5423 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005424 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5425 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5426 // it should go thru setDesiredActiveConfig, similar to primary display.
5427 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5428 const auto displayId = display->getId();
5429 LOG_ALWAYS_FATAL_IF(!displayId);
5430
5431 HWC2::VsyncPeriodChangeConstraints constraints;
5432 constraints.desiredTimeNanos = systemTime();
5433 constraints.seamlessRequired = false;
5434
5435 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
5436 getHwComposer().setActiveConfigWithConstraints(*displayId, allowedConfigs[0], constraints,
5437 &timeline);
5438 if (timeline.refreshRequired) {
5439 repaintEverythingForHWC();
5440 }
5441
5442 auto configId = HwcConfigIndexType(allowedConfigs[0]);
5443 display->setActiveConfig(configId);
5444 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId);
Ady Abraham838de062019-02-04 10:24:03 -08005445 return;
5446 }
5447
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005448 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5449 allowedConfigs.end());
5450 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5451 return;
5452 }
5453
Ady Abraham838de062019-02-04 10:24:03 -08005454 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005455 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5456
5457 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5458 // that listeners that care about a change in allowed configs can get the notification.
5459 // Giving current ActiveConfig so that most other listeners would just drop the event
5460 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5461 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005462
Ady Abraham2139f732019-11-13 18:56:40 -08005463 // Prepare the parameters needed for RefreshRateConfigs::setPolicy. This will change to just
5464 // passthrough once DisplayManager provide these parameters directly.
5465 const auto refreshRate =
5466 mRefreshRateConfigs->getRefreshRateFromConfigId(HwcConfigIndexType(allowedConfigs[0]));
5467 const auto defaultModeId = refreshRate.configId;
5468 auto minRefreshRateFps = refreshRate.fps;
5469 auto maxRefreshRateFps = minRefreshRateFps;
5470
5471 for (auto config : allowedConfigs) {
5472 const auto configRefreshRate =
5473 mRefreshRateConfigs->getRefreshRateFromConfigId(HwcConfigIndexType(config));
5474 if (configRefreshRate.fps < minRefreshRateFps) {
5475 minRefreshRateFps = configRefreshRate.fps;
5476 } else if (configRefreshRate.fps > maxRefreshRateFps) {
5477 maxRefreshRateFps = configRefreshRate.fps;
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005478 }
Ady Abraham2139f732019-11-13 18:56:40 -08005479 }
5480 mRefreshRateConfigs->setPolicy(defaultModeId, minRefreshRateFps, maxRefreshRateFps);
5481
5482 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5483 auto configId = mScheduler->getPreferredConfigId();
5484 auto preferredRefreshRate = configId
5485 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5486 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5487 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5488 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5489 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5490 ALOGV("switching to Scheduler preferred config %d",
5491 preferredRefreshRate.configId.value());
5492 setDesiredActiveConfig(
5493 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5494 } else {
5495 // Set the highest allowed config
5496 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5497 Scheduler::ConfigEvent::Changed});
5498 }
5499 } else {
5500 if (!allowedConfigs.empty()) {
5501 ALOGV("switching to config %d", allowedConfigs[0]);
5502 auto configId = HwcConfigIndexType(allowedConfigs[0]);
5503 setDesiredActiveConfig({configId, Scheduler::ConfigEvent::Changed});
5504 }
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005505 }
Ady Abraham838de062019-02-04 10:24:03 -08005506}
5507
Dominik Laskowski22488f62019-03-28 09:53:04 -07005508status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005509 const std::vector<int32_t>& allowedConfigs) {
5510 ATRACE_CALL();
5511
Dominik Laskowski22488f62019-03-28 09:53:04 -07005512 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005513 return BAD_VALUE;
5514 }
5515
Ady Abraham34392f72019-04-10 11:29:27 -07005516 if (mDebugDisplayConfigSetByBackdoor) {
5517 // ignore this request as config is overridden by backdoor
5518 return NO_ERROR;
5519 }
5520
Ady Abrahama3129fb2019-10-18 14:17:23 -07005521 postMessageSync(new LambdaMessage([&]() {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005522 const auto display = getDisplayDeviceLocked(displayToken);
5523 if (!display) {
5524 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5525 displayToken.get());
5526 } else if (display->isVirtual()) {
5527 ALOGW("Attempt to set allowed display configs for virtual display");
5528 } else {
Ady Abrahama3129fb2019-10-18 14:17:23 -07005529 Mutex::Autolock lock(mStateLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005530 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5531 }
Ady Abraham838de062019-02-04 10:24:03 -08005532 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005533
Ady Abraham838de062019-02-04 10:24:03 -08005534 return NO_ERROR;
5535}
5536
Dominik Laskowski22488f62019-03-28 09:53:04 -07005537status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005538 std::vector<int32_t>* outAllowedConfigs) {
5539 ATRACE_CALL();
5540
Dominik Laskowski22488f62019-03-28 09:53:04 -07005541 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005542 return BAD_VALUE;
5543 }
5544
Dominik Laskowski22488f62019-03-28 09:53:04 -07005545 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005546
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005547 const auto display = getDisplayDeviceLocked(displayToken);
5548 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005549 return NAME_NOT_FOUND;
5550 }
5551
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005552 if (display->isPrimary()) {
Ady Abraham2139f732019-11-13 18:56:40 -08005553 outAllowedConfigs->reserve(mAllowedDisplayConfigs.size());
5554 for (auto configId : mAllowedDisplayConfigs) {
5555 outAllowedConfigs->push_back(configId.value());
5556 }
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005557 }
5558
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005559 return NO_ERROR;
5560}
5561
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005562void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005563 mFlinger->setInputWindowsFinished();
5564}
5565
Robert Carrc0df3122019-04-11 13:18:21 -07005566sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5567 BBinder *b = handle->localBinder();
5568 if (b == nullptr) {
5569 return nullptr;
5570 }
5571 auto it = mLayersByLocalBinderToken.find(b);
5572 if (it != mLayersByLocalBinderToken.end()) {
5573 return it->second.promote();
5574 }
5575 return nullptr;
5576}
5577
Dominik Laskowski75848362019-11-11 17:57:20 -08005578void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005579 mNumLayers++;
5580 mScheduler->registerLayer(layer);
5581}
5582
5583void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5584 mNumLayers--;
5585 mOffscreenLayers.erase(layer);
5586}
5587
Alec Mouri4545a8a2019-08-08 20:05:32 -07005588void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5589 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5590}
5591
Vishnu Nairb13bb952019-11-15 10:24:08 -08005592status_t SurfaceFlinger::setGlobalShadowSettings(const half4& /*ambientColor*/,
5593 const half4& /*spotColor*/, float /*lightPosY*/,
5594 float /*lightPosZ*/, float /*lightRadius*/) {
5595 return NO_ERROR;
5596}
5597
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005598} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005599
Mathias Agopian3f844832013-08-07 21:24:32 -07005600#if defined(__gl_h_)
5601#error "don't include gl/gl.h in this file"
5602#endif
5603
5604#if defined(__gl2_h_)
5605#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005606#endif