blob: 99a9265992f5502a9d4b6fcb7855a7728580307c [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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopiana4912602012-07-12 14:25:33 -070075#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070076#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070077#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include "Effects/Daltonizer.h"
80
Mathias Agopian875d8e12013-06-07 15:35:48 -070081#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#define DISPLAY_COUNT 1
85
Mathias Agopianfee2b462013-07-03 12:34:01 -070086/*
87 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 * black pixels.
89 */
90#define DEBUG_SCREENSHOTS false
91
Mathias Agopianca088332013-03-28 17:44:13 -070092EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93
Evgenii Stepanov22819272016-07-14 14:17:24 -070094// Workaround for b/30067360: /proc/self/environ inaccessible in SurfaceFlinger
95// => ASan fails to read ASAN_OPTIONS => alloc-dealloc-mismatch bug is not
96// suppressed and prevents the device from booting.
97#ifndef __has_feature
98#define __has_feature(x) 0
99#endif
100#if __has_feature(address_sanitizer)
101__attribute__((visibility("default")))
102extern "C" const char* __asan_default_options() {
103 return "alloc_dealloc_mismatch=0";
104}
105#endif
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109// This is the phase offset in nanoseconds of the software vsync event
110// relative to the vsync event reported by HWComposer. The software vsync
111// event is when SurfaceFlinger and Choreographer-based applications run each
112// frame.
113//
114// This phase offset allows adjustment of the minimum latency from application
115// wake-up (by Choregographer) time to the time at which the resulting window
116// image is displayed. This value may be either positive (after the HW vsync)
117// or negative (before the HW vsync). Setting it to 0 will result in a
118// minimum latency of two vsync periods because the app and SurfaceFlinger
119// will run just after the HW vsync. Setting it to a positive number will
120// result in the minimum latency being:
121//
122// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
123//
124// Note that reducing this latency makes it more likely for the applications
125// to not have their window content image ready in time. When this happens
126// the latency will end up being an additional vsync period, and animations
127// will hiccup. Therefore, this latency should be tuned somewhat
128// conservatively (or at least with awareness of the trade-off being made).
129static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
130
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700131// This is the phase offset at which SurfaceFlinger's composition runs.
132static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134// ---------------------------------------------------------------------------
135
Mathias Agopian99b49842011-06-27 16:05:52 -0700136const String16 sHardwareTest("android.permission.HARDWARE_TEST");
137const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
138const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
139const String16 sDump("android.permission.DUMP");
140
141// ---------------------------------------------------------------------------
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700144 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700146 mTransactionPending(false),
147 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700148 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700149 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700150 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800151 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800152 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800154 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800155 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700157 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700158 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700159 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700160 mDebugInSwapBuffers(0),
161 mLastSwapBufferTime(0),
162 mDebugInTransaction(0),
163 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700164 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700165 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700166 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000167 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700168 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700169 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800170 mHasColorMatrix(false),
171 mHasPoweredOff(false),
172 mFrameBuckets(),
173 mTotalTime(0),
174 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175{
Steve Blocka19954a2012-01-04 20:05:49 +0000176 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177
178 // debugging stuff...
179 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180
Mathias Agopianb4b17302013-03-20 18:36:41 -0700181 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700182 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184 property_get("debug.sf.showupdates", value, "0");
185 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700186
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700187 property_get("debug.sf.ddms", value, "0");
188 mDebugDDMS = atoi(value);
189 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700190 if (!startDdmConnection()) {
191 // start failed, and DDMS debugging not enabled
192 mDebugDDMS = 0;
193 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700194 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700195 ALOGI_IF(mDebugRegion, "showupdates enabled");
196 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700197
198 property_get("debug.sf.disable_backpressure", value, "0");
199 mPropagateBackpressure = !atoi(value);
200 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700201
202 property_get("debug.sf.disable_hwc_vds", value, "0");
203 mUseHwcVirtualDisplays = !atoi(value);
204 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205}
206
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800207void SurfaceFlinger::onFirstRef()
208{
209 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800210}
211
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800212SurfaceFlinger::~SurfaceFlinger()
213{
Mathias Agopiana4912602012-07-12 14:25:33 -0700214 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
215 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
216 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800217}
218
Dan Stozac7014012014-02-14 15:03:43 -0800219void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800220{
221 // the window manager died on us. prepare its eulogy.
222
Andy McFadden13a082e2012-08-24 10:16:42 -0700223 // restore initial conditions (default device unblank, etc)
224 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800225
226 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700227 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800228}
229
Mathias Agopian7e27f052010-05-28 14:22:23 -0700230sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800231{
Mathias Agopian96f08192010-06-02 23:28:45 -0700232 sp<ISurfaceComposerClient> bclient;
233 sp<Client> client(new Client(this));
234 status_t err = client->initCheck();
235 if (err == NO_ERROR) {
236 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800237 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800238 return bclient;
239}
240
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700241sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
242 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700243{
244 class DisplayToken : public BBinder {
245 sp<SurfaceFlinger> flinger;
246 virtual ~DisplayToken() {
247 // no more references, this display must be terminated
248 Mutex::Autolock _l(flinger->mStateLock);
249 flinger->mCurrentState.displays.removeItem(this);
250 flinger->setTransactionFlags(eDisplayTransactionNeeded);
251 }
252 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700253 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700254 : flinger(flinger) {
255 }
256 };
257
258 sp<BBinder> token = new DisplayToken(this);
259
260 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700261 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700262 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700263 mCurrentState.displays.add(token, info);
Irvelffc9efc2016-07-27 15:16:37 -0700264 mInterceptor.saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700265 return token;
266}
267
Jesse Hall6c913be2013-08-08 12:15:49 -0700268void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
269 Mutex::Autolock _l(mStateLock);
270
271 ssize_t idx = mCurrentState.displays.indexOfKey(display);
272 if (idx < 0) {
273 ALOGW("destroyDisplay: invalid display token");
274 return;
275 }
276
277 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
278 if (!info.isVirtualDisplay()) {
279 ALOGE("destroyDisplay called for non-virtual display");
280 return;
281 }
Irvelffc9efc2016-07-27 15:16:37 -0700282 mInterceptor.saveDisplayDeletion(info.displayId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700283 mCurrentState.displays.removeItemsAt(idx);
284 setTransactionFlags(eDisplayTransactionNeeded);
285}
286
Jesse Hall692c7232012-11-08 15:41:56 -0800287void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800288 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800289 ALOGW_IF(mBuiltinDisplays[type],
290 "Overwriting display token for display type %d", type);
291 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800292 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700293 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800294 mCurrentState.displays.add(mBuiltinDisplays[type], info);
Irvelffc9efc2016-07-27 15:16:37 -0700295 mInterceptor.saveDisplayCreation(info);
Jesse Hall692c7232012-11-08 15:41:56 -0800296}
297
Mathias Agopiane57f2922012-08-09 16:29:12 -0700298sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700299 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700300 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
301 return NULL;
302 }
Jesse Hall692c7232012-11-08 15:41:56 -0800303 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700304}
305
Jamie Gennis9a78c902011-01-12 18:30:40 -0800306sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
307{
308 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
309 return gba;
310}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700311
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800312void SurfaceFlinger::bootFinished()
313{
314 const nsecs_t now = systemTime();
315 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000316 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700317 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700318
319 // wait patiently for the window manager death
320 const String16 name("window");
321 sp<IBinder> window(defaultServiceManager()->getService(name));
322 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700323 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700324 }
325
326 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700327 // formerly we would just kill the process, but we now ask it to exit so it
328 // can choose where to stop the animation.
329 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700330
331 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
332 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
333 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800334}
335
Mathias Agopian3f844832013-08-07 21:24:32 -0700336void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700337 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700338 RenderEngine& engine;
339 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700340 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700341 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
342 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700343 }
344 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700345 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700346 return true;
347 }
348 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700349 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700350}
351
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700352class DispSyncSource : public VSyncSource, private DispSync::Callback {
353public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700354 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000355 const char* name) :
356 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700357 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700358 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000359 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
360 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700361 mDispSync(dispSync),
362 mCallbackMutex(),
363 mCallback(),
364 mVsyncMutex(),
365 mPhaseOffset(phaseOffset),
366 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700367
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700368 virtual ~DispSyncSource() {}
369
370 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700371 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700372 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000373 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700374 static_cast<DispSync::Callback*>(this));
375 if (err != NO_ERROR) {
376 ALOGE("error registering vsync callback: %s (%d)",
377 strerror(-err), err);
378 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700379 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700380 } else {
381 status_t err = mDispSync->removeEventListener(
382 static_cast<DispSync::Callback*>(this));
383 if (err != NO_ERROR) {
384 ALOGE("error unregistering vsync callback: %s (%d)",
385 strerror(-err), err);
386 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700387 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700388 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700389 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700390 }
391
392 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700393 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700394 mCallback = callback;
395 }
396
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700397 virtual void setPhaseOffset(nsecs_t phaseOffset) {
398 Mutex::Autolock lock(mVsyncMutex);
399
400 // Normalize phaseOffset to [0, period)
401 auto period = mDispSync->getPeriod();
402 phaseOffset %= period;
403 if (phaseOffset < 0) {
404 // If we're here, then phaseOffset is in (-period, 0). After this
405 // operation, it will be in (0, period)
406 phaseOffset += period;
407 }
408 mPhaseOffset = phaseOffset;
409
410 // If we're not enabled, we don't need to mess with the listeners
411 if (!mEnabled) {
412 return;
413 }
414
415 // Remove the listener with the old offset
416 status_t err = mDispSync->removeEventListener(
417 static_cast<DispSync::Callback*>(this));
418 if (err != NO_ERROR) {
419 ALOGE("error unregistering vsync callback: %s (%d)",
420 strerror(-err), err);
421 }
422
423 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000424 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700425 static_cast<DispSync::Callback*>(this));
426 if (err != NO_ERROR) {
427 ALOGE("error registering vsync callback: %s (%d)",
428 strerror(-err), err);
429 }
430 }
431
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432private:
433 virtual void onDispSyncEvent(nsecs_t when) {
434 sp<VSyncSource::Callback> callback;
435 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700436 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700437 callback = mCallback;
438
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700439 if (mTraceVsync) {
440 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700441 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700442 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700443 }
444
445 if (callback != NULL) {
446 callback->onVSyncEvent(when);
447 }
448 }
449
Tim Murray4a4e4a22016-04-19 16:29:23 +0000450 const char* const mName;
451
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700452 int mValue;
453
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700454 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700455 const String8 mVsyncOnLabel;
456 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700457
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700459
460 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700462
463 Mutex mVsyncMutex; // Protects the following
464 nsecs_t mPhaseOffset;
465 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700466};
467
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700468class InjectVSyncSource : public VSyncSource {
469public:
470 InjectVSyncSource() {}
471
472 virtual ~InjectVSyncSource() {}
473
474 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
475 std::lock_guard<std::mutex> lock(mCallbackMutex);
476 mCallback = callback;
477 }
478
479 virtual void onInjectSyncEvent(nsecs_t when) {
480 std::lock_guard<std::mutex> lock(mCallbackMutex);
481 mCallback->onVSyncEvent(when);
482 }
483
484 virtual void setVSyncEnabled(bool) {}
485 virtual void setPhaseOffset(nsecs_t) {}
486
487private:
488 std::mutex mCallbackMutex; // Protects the following
489 sp<VSyncSource::Callback> mCallback;
490};
491
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700492void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700493 ALOGI( "SurfaceFlinger's main thread ready to run. "
494 "Initializing graphics H/W...");
495
Dan Stoza9e56aa02015-11-02 13:00:03 -0800496 { // Autolock scope
497 Mutex::Autolock _l(mStateLock);
498
499 // initialize EGL for the default display
500 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
501 eglInitialize(mEGLDisplay, NULL, NULL);
502
503 // start the EventThread
504 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
505 vsyncPhaseOffsetNs, true, "app");
Irvelab046852016-07-28 11:23:08 -0700506 mEventThread = new EventThread(vsyncSrc, *this, false);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800507 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
508 sfVsyncPhaseOffsetNs, true, "sf");
Irvelab046852016-07-28 11:23:08 -0700509 mSFEventThread = new EventThread(sfVsyncSrc, *this, true);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800510 mEventQueue.setEventThread(mSFEventThread);
511
Tim Murrayacff43d2016-07-29 13:57:24 -0700512 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700513 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700514 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700515 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
516 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
517 }
518
Dan Stoza9e56aa02015-11-02 13:00:03 -0800519 // Get a RenderEngine for the given display / config (can't fail)
520 mRenderEngine = RenderEngine::create(mEGLDisplay,
521 HAL_PIXEL_FORMAT_RGBA_8888);
522 }
523
524 // Drop the state lock while we initialize the hardware composer. We drop
525 // the lock because on creation, it will call back into SurfaceFlinger to
526 // initialize the primary display.
527 mHwc = new HWComposer(this);
528 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
529
Jesse Hall692c7232012-11-08 15:41:56 -0800530 Mutex::Autolock _l(mStateLock);
531
Mathias Agopian875d8e12013-06-07 15:35:48 -0700532 // retrieve the EGL context that was selected/created
533 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700534
Mathias Agopianda27af92012-09-13 18:17:13 -0700535 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
536 "couldn't create EGLContext");
537
Dan Stoza9e56aa02015-11-02 13:00:03 -0800538 // make the GLContext current so that we can create textures when creating
539 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700540 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
541
Jamie Gennisd1700752013-10-14 12:22:52 -0700542 mEventControlThread = new EventControlThread(this);
543 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
544
Mathias Agopian92a979a2012-08-02 18:32:23 -0700545 // initialize our drawing state
546 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700547
Andy McFadden13a082e2012-08-24 10:16:42 -0700548 // set initial conditions (e.g. unblank default device)
549 initializeDisplays();
550
Dan Stoza4e637772016-07-28 13:31:51 -0700551 mRenderEngine->primeCache();
552
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700553 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700554 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555
Dan Stoza9e56aa02015-11-02 13:00:03 -0800556 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700557}
558
Mathias Agopiana67e4182012-06-19 17:26:12 -0700559void SurfaceFlinger::startBootAnim() {
560 // start boot animation
561 property_set("service.bootanim.exit", "0");
562 property_set("ctl.start", "bootanim");
563}
564
Mathias Agopian875d8e12013-06-07 15:35:48 -0700565size_t SurfaceFlinger::getMaxTextureSize() const {
566 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700567}
568
Mathias Agopian875d8e12013-06-07 15:35:48 -0700569size_t SurfaceFlinger::getMaxViewportDims() const {
570 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700571}
572
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800573// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800574
Jamie Gennis582270d2011-08-17 18:19:00 -0700575bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800576 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800577 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800578 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700579 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800580}
581
Dan Stoza7f7da322014-05-02 15:26:25 -0700582status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
583 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700584 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700585 return BAD_VALUE;
586 }
587
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500588 if (!display.get())
589 return NAME_NOT_FOUND;
590
Jesse Hall692c7232012-11-08 15:41:56 -0800591 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700592 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800593 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700594 type = i;
595 break;
596 }
597 }
598
599 if (type < 0) {
600 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700601 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700602
Mathias Agopian8b736f12012-08-13 17:54:26 -0700603 // TODO: Not sure if display density should handled by SF any longer
604 class Density {
605 static int getDensityFromProperty(char const* propName) {
606 char property[PROPERTY_VALUE_MAX];
607 int density = 0;
608 if (property_get(propName, property, NULL) > 0) {
609 density = atoi(property);
610 }
611 return density;
612 }
613 public:
614 static int getEmuDensity() {
615 return getDensityFromProperty("qemu.sf.lcd_density"); }
616 static int getBuildDensity() {
617 return getDensityFromProperty("ro.sf.lcd_density"); }
618 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700619
Dan Stoza7f7da322014-05-02 15:26:25 -0700620 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700621
Dan Stoza9e56aa02015-11-02 13:00:03 -0800622 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700623 DisplayInfo info = DisplayInfo();
624
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625 float xdpi = hwConfig->getDpiX();
626 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700627
628 if (type == DisplayDevice::DISPLAY_PRIMARY) {
629 // The density of the device is provided by a build property
630 float density = Density::getBuildDensity() / 160.0f;
631 if (density == 0) {
632 // the build doesn't provide a density -- this is wrong!
633 // use xdpi instead
634 ALOGE("ro.sf.lcd_density must be defined as a build property");
635 density = xdpi / 160.0f;
636 }
637 if (Density::getEmuDensity()) {
638 // if "qemu.sf.lcd_density" is specified, it overrides everything
639 xdpi = ydpi = density = Density::getEmuDensity();
640 density /= 160.0f;
641 }
642 info.density = density;
643
644 // TODO: this needs to go away (currently needed only by webkit)
645 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
646 info.orientation = hw->getOrientation();
647 } else {
648 // TODO: where should this value come from?
649 static const int TV_DENSITY = 213;
650 info.density = TV_DENSITY / 160.0f;
651 info.orientation = 0;
652 }
653
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654 info.w = hwConfig->getWidth();
655 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700656 info.xdpi = xdpi;
657 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800658 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700659 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800660
Andy McFadden91b2ca82014-06-13 14:04:23 -0700661 // This is how far in advance a buffer must be queued for
662 // presentation at a given time. If you want a buffer to appear
663 // on the screen at time N, you must submit the buffer before
664 // (N - presentationDeadline).
665 //
666 // Normally it's one full refresh period (to give SF a chance to
667 // latch the buffer), but this can be reduced by configuring a
668 // DispSync offset. Any additional delays introduced by the hardware
669 // composer or panel must be accounted for here.
670 //
671 // We add an additional 1ms to allow for processing time and
672 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673 info.presentationDeadline = hwConfig->getVsyncPeriod() -
674 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700675
676 // All non-virtual displays are currently considered secure.
677 info.secure = true;
678
Michael Wright28f24d02016-07-12 13:30:53 -0700679 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700680 }
681
Dan Stoza7f7da322014-05-02 15:26:25 -0700682 return NO_ERROR;
683}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700684
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800685status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700686 DisplayStatInfo* stats) {
687 if (stats == NULL) {
688 return BAD_VALUE;
689 }
690
691 // FIXME for now we always return stats for the primary display
692 memset(stats, 0, sizeof(*stats));
693 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
694 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
695 return NO_ERROR;
696}
697
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700698int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700699 sp<DisplayDevice> device(getDisplayDevice(display));
700 if (device != NULL) {
701 return device->getActiveConfig();
702 }
703 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700704}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700705
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700706void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
707 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
708 this);
709 int32_t type = hw->getDisplayType();
710 int currentMode = hw->getActiveConfig();
711
712 if (mode == currentMode) {
713 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
714 return;
715 }
716
717 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
718 ALOGW("Trying to set config for virtual display");
719 return;
720 }
721
722 hw->setActiveConfig(mode);
723 getHwComposer().setActiveConfig(type, mode);
724}
725
726status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
727 class MessageSetActiveConfig: public MessageBase {
728 SurfaceFlinger& mFlinger;
729 sp<IBinder> mDisplay;
730 int mMode;
731 public:
732 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
733 int mode) :
734 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
735 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700736 Vector<DisplayInfo> configs;
737 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700738 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700739 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700740 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700741 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700742 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700743 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
744 if (hw == NULL) {
745 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700746 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700747 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
748 ALOGW("Attempt to set active config = %d for virtual display",
749 mMode);
750 } else {
751 mFlinger.setActiveConfigInternal(hw, mMode);
752 }
753 return true;
754 }
755 };
756 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
757 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700758 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700759}
Michael Wright28f24d02016-07-12 13:30:53 -0700760status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
761 Vector<android_color_mode_t>* outColorModes) {
762 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
763 return BAD_VALUE;
764 }
765
766 if (!display.get()) {
767 return NAME_NOT_FOUND;
768 }
769
770 int32_t type = NAME_NOT_FOUND;
771 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
772 if (display == mBuiltinDisplays[i]) {
773 type = i;
774 break;
775 }
776 }
777
778 if (type < 0) {
779 return type;
780 }
781
782 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
783 outColorModes->clear();
784 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
785
786 return NO_ERROR;
787}
788
789android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
790 sp<DisplayDevice> device(getDisplayDevice(display));
791 if (device != nullptr) {
792 return device->getActiveColorMode();
793 }
794 return static_cast<android_color_mode_t>(BAD_VALUE);
795}
796
797void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
798 android_color_mode_t mode) {
799 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
800 this);
801 int32_t type = hw->getDisplayType();
802 android_color_mode_t currentMode = hw->getActiveColorMode();
803
804 if (mode == currentMode) {
805 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
806 return;
807 }
808
809 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
810 ALOGW("Trying to set config for virtual display");
811 return;
812 }
813
814 hw->setActiveColorMode(mode);
815 getHwComposer().setActiveColorMode(type, mode);
816}
817
818
819status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
820 android_color_mode_t colorMode) {
821 class MessageSetActiveColorMode: public MessageBase {
822 SurfaceFlinger& mFlinger;
823 sp<IBinder> mDisplay;
824 android_color_mode_t mMode;
825 public:
826 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
827 android_color_mode_t mode) :
828 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
829 virtual bool handler() {
830 Vector<android_color_mode_t> modes;
831 mFlinger.getDisplayColorModes(mDisplay, &modes);
832 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
833 if (mMode < 0 || !exists) {
834 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
835 mDisplay.get());
836 return true;
837 }
838 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
839 if (hw == nullptr) {
840 ALOGE("Attempt to set active color mode = %d for null display %p",
841 mMode, mDisplay.get());
842 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
843 ALOGW("Attempt to set active color mode= %d for virtual display",
844 mMode);
845 } else {
846 mFlinger.setActiveColorModeInternal(hw, mMode);
847 }
848 return true;
849 }
850 };
851 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
852 postMessageSync(msg);
853 return NO_ERROR;
854}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700855
Svetoslavd85084b2014-03-20 10:28:31 -0700856status_t SurfaceFlinger::clearAnimationFrameStats() {
857 Mutex::Autolock _l(mStateLock);
858 mAnimFrameTracker.clearStats();
859 return NO_ERROR;
860}
861
862status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
863 Mutex::Autolock _l(mStateLock);
864 mAnimFrameTracker.getStats(outStats);
865 return NO_ERROR;
866}
867
Dan Stozac4f471e2016-03-24 09:31:08 -0700868status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
869 HdrCapabilities* outCapabilities) const {
870 Mutex::Autolock _l(mStateLock);
871
872 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
873 if (displayDevice == nullptr) {
874 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
875 return BAD_VALUE;
876 }
877
878 std::unique_ptr<HdrCapabilities> capabilities =
879 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
880 if (capabilities) {
881 std::swap(*outCapabilities, *capabilities);
882 } else {
883 return BAD_VALUE;
884 }
885
886 return NO_ERROR;
887}
888
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700889status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
890 if (enable == mInjectVSyncs) {
891 return NO_ERROR;
892 }
893
894 if (enable) {
895 mInjectVSyncs = enable;
896 ALOGV("VSync Injections enabled");
897 if (mVSyncInjector.get() == nullptr) {
898 mVSyncInjector = new InjectVSyncSource();
Irvelab046852016-07-28 11:23:08 -0700899 mInjectorEventThread = new EventThread(mVSyncInjector, *this, false);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700900 }
901 mEventQueue.setEventThread(mInjectorEventThread);
902 } else {
903 mInjectVSyncs = enable;
904 ALOGV("VSync Injections disabled");
905 mEventQueue.setEventThread(mSFEventThread);
906 mVSyncInjector.clear();
907 }
908 return NO_ERROR;
909}
910
911status_t SurfaceFlinger::injectVSync(nsecs_t when) {
912 if (!mInjectVSyncs) {
913 ALOGE("VSync Injections not enabled");
914 return BAD_VALUE;
915 }
916 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
917 ALOGV("Injecting VSync inside SurfaceFlinger");
918 mVSyncInjector->onInjectSyncEvent(when);
919 }
920 return NO_ERROR;
921}
922
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800923// ----------------------------------------------------------------------------
924
925sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800926 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700927}
928
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800929// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800930
931void SurfaceFlinger::waitForEvent() {
932 mEventQueue.waitMessage();
933}
934
935void SurfaceFlinger::signalTransaction() {
936 mEventQueue.invalidate();
937}
938
939void SurfaceFlinger::signalLayerUpdate() {
940 mEventQueue.invalidate();
941}
942
943void SurfaceFlinger::signalRefresh() {
944 mEventQueue.refresh();
945}
946
947status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800948 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800949 return mEventQueue.postMessage(msg, reltime);
950}
951
952status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800953 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800954 status_t res = mEventQueue.postMessage(msg, reltime);
955 if (res == NO_ERROR) {
956 msg->wait();
957 }
958 return res;
959}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800960
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700961void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700962 do {
963 waitForEvent();
964 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800965}
966
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700967void SurfaceFlinger::enableHardwareVsync() {
968 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700969 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700970 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700971 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
972 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700973 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700974 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700975}
976
Jesse Hall948fe0c2013-10-14 12:56:09 -0700977void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700978 Mutex::Autolock _l(mHWVsyncLock);
979
Jesse Hall948fe0c2013-10-14 12:56:09 -0700980 if (makeAvailable) {
981 mHWVsyncAvailable = true;
982 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700983 // Hardware vsync is not currently available, so abort the resync
984 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700985 return;
986 }
987
Dan Stoza9e56aa02015-11-02 13:00:03 -0800988 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
989 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700990
991 mPrimaryDispSync.reset();
992 mPrimaryDispSync.setPeriod(period);
993
994 if (!mPrimaryHWVsyncEnabled) {
995 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700996 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
997 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700998 mPrimaryHWVsyncEnabled = true;
999 }
1000}
1001
Jesse Hall948fe0c2013-10-14 12:56:09 -07001002void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001003 Mutex::Autolock _l(mHWVsyncLock);
1004 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001005 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1006 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001007 mPrimaryDispSync.endResync();
1008 mPrimaryHWVsyncEnabled = false;
1009 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001010 if (makeUnavailable) {
1011 mHWVsyncAvailable = false;
1012 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001013}
1014
Tim Murray4a4e4a22016-04-19 16:29:23 +00001015void SurfaceFlinger::resyncWithRateLimit() {
1016 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1017 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001018 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001019 }
1020}
1021
Dan Stoza9e56aa02015-11-02 13:00:03 -08001022void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001023 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001024
Jamie Gennisd1700752013-10-14 12:22:52 -07001025 { // Scope for the lock
1026 Mutex::Autolock _l(mHWVsyncLock);
1027 if (type == 0 && mPrimaryHWVsyncEnabled) {
1028 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001029 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001030 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001031
1032 if (needsHwVsync) {
1033 enableHardwareVsync();
1034 } else {
1035 disableHardwareVsync(false);
1036 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001037}
1038
Dan Stoza9e56aa02015-11-02 13:00:03 -08001039void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1040 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1041 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1042 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001043
Dan Stoza9e56aa02015-11-02 13:00:03 -08001044 // All non-virtual displays are currently considered secure.
1045 bool isSecure = true;
1046
1047 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1048 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1049 wp<IBinder> token = mBuiltinDisplays[type];
1050
1051 sp<IGraphicBufferProducer> producer;
1052 sp<IGraphicBufferConsumer> consumer;
1053 BufferQueue::createBufferQueue(&producer, &consumer,
1054 new GraphicBufferAlloc());
1055
1056 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1057 DisplayDevice::DISPLAY_PRIMARY, consumer);
1058 sp<DisplayDevice> hw = new DisplayDevice(this,
1059 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1060 producer, mRenderEngine->getEGLConfig());
1061 mDisplays.add(token, hw);
1062 } else {
1063 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001064 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001065 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001066 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001067 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001068 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1069 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001070 }
1071 setTransactionFlags(eDisplayTransactionNeeded);
1072
Andy McFadden9e9689c2012-10-10 18:17:51 -07001073 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001074 }
Mathias Agopian86303202012-07-24 22:46:10 -07001075}
1076
Dan Stoza9e56aa02015-11-02 13:00:03 -08001077void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001078 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001079 getHwComposer().setVsyncEnabled(disp,
1080 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001081}
1082
Mathias Agopian4fec8732012-06-29 14:12:52 -07001083void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001084 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001085 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001086 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001087 bool frameMissed = !mHadClientComposition &&
1088 mPreviousPresentFence != Fence::NO_FENCE &&
1089 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1090 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001091 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001092 signalLayerUpdate();
1093 break;
1094 }
1095
Dan Stoza6b9454d2014-11-07 16:00:59 -08001096 bool refreshNeeded = handleMessageTransaction();
1097 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001098 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001099 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001100 // Signal a refresh if a transaction modified the window state,
1101 // a new buffer was latched, or if HWC has requested a full
1102 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001103 signalRefresh();
1104 }
1105 break;
1106 }
1107 case MessageQueue::REFRESH: {
1108 handleMessageRefresh();
1109 break;
1110 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001111 }
1112}
1113
Dan Stoza6b9454d2014-11-07 16:00:59 -08001114bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001115 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001116 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001117 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001118 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001119 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001120 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001121}
1122
Dan Stoza6b9454d2014-11-07 16:00:59 -08001123bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001124 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001125 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001126}
1127
1128void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001129 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001130
Pablo Ceballos40845df2016-01-25 17:41:15 -08001131 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001132
Dan Stoza05dacfb2016-07-01 13:33:38 -07001133 preComposition();
1134 rebuildLayerStacks();
1135 setUpHWComposer();
1136 doDebugFlashRegions();
1137 doComposition();
1138 postComposition(refreshStartTime);
1139
1140 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001141
1142 mHadClientComposition = false;
1143 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1144 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1145 mHadClientComposition = mHadClientComposition ||
1146 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1147 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001148
Dan Stoza9e56aa02015-11-02 13:00:03 -08001149 // Release any buffers which were replaced this frame
1150 for (auto& layer : mLayersWithQueuedFrames) {
1151 layer->releasePendingBuffer();
1152 }
1153 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001154}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001155
Mathias Agopiancd60f992012-08-16 16:28:27 -07001156void SurfaceFlinger::doDebugFlashRegions()
1157{
1158 // is debugging enabled
1159 if (CC_LIKELY(!mDebugRegion))
1160 return;
1161
1162 const bool repaintEverything = mRepaintEverything;
1163 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1164 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001165 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001166 // transform the dirty region into this screen's coordinate space
1167 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1168 if (!dirtyRegion.isEmpty()) {
1169 // redraw the whole screen
1170 doComposeSurfaces(hw, Region(hw->bounds()));
1171
1172 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001173 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001174 RenderEngine& engine(getRenderEngine());
1175 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1176
Mathias Agopianda27af92012-09-13 18:17:13 -07001177 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001178 }
1179 }
1180 }
1181
1182 postFramebuffer();
1183
1184 if (mDebugRegion > 1) {
1185 usleep(mDebugRegion * 1000);
1186 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001187
Dan Stoza9e56aa02015-11-02 13:00:03 -08001188 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001189 auto& displayDevice = mDisplays[displayId];
1190 if (!displayDevice->isDisplayOn()) {
1191 continue;
1192 }
1193
1194 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001195 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1196 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001197 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001198}
1199
1200void SurfaceFlinger::preComposition()
1201{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001202 ATRACE_CALL();
1203 ALOGV("preComposition");
1204
Mathias Agopiancd60f992012-08-16 16:28:27 -07001205 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001206 const LayerVector& layers(mDrawingState.layersSortedByZ);
1207 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001208 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001209 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001210 needExtraInvalidate = true;
1211 }
1212 }
1213 if (needExtraInvalidate) {
1214 signalLayerUpdate();
1215 }
1216}
1217
Pablo Ceballos40845df2016-01-25 17:41:15 -08001218void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001219{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001220 ATRACE_CALL();
1221 ALOGV("postComposition");
1222
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001223 const LayerVector& layers(mDrawingState.layersSortedByZ);
1224 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001225 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001226 bool frameLatched = layers[i]->onPostComposition();
1227 if (frameLatched) {
1228 recordBufferingStats(layers[i]->getName().string(),
1229 layers[i]->getOccupancyHistory(false));
1230 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001231 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001232
Dan Stoza9e56aa02015-11-02 13:00:03 -08001233 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001234
1235 if (presentFence->isValid()) {
1236 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1237 enableHardwareVsync();
1238 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001239 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001240 }
1241 }
1242
Dan Stozab90cf072015-03-05 11:05:59 -08001243 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001244 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001245 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001246 enableHardwareVsync();
1247 }
1248 }
1249
Pablo Ceballos40845df2016-01-25 17:41:15 -08001250 mFenceTracker.addFrame(refreshStartTime, presentFence,
1251 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1252
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001253 if (mAnimCompositionPending) {
1254 mAnimCompositionPending = false;
1255
Jesse Halla9a1b002013-02-27 16:39:25 -08001256 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001257 mAnimFrameTracker.setActualPresentFence(presentFence);
1258 } else {
1259 // The HWC doesn't support present fences, so use the refresh
1260 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001261 nsecs_t presentTime =
1262 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001263 mAnimFrameTracker.setActualPresentTime(presentTime);
1264 }
1265 mAnimFrameTracker.advanceFrame();
1266 }
Dan Stozab90cf072015-03-05 11:05:59 -08001267
1268 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1269 return;
1270 }
1271
1272 nsecs_t currentTime = systemTime();
1273 if (mHasPoweredOff) {
1274 mHasPoweredOff = false;
1275 } else {
1276 nsecs_t period = mPrimaryDispSync.getPeriod();
1277 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1278 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1279 if (numPeriods < NUM_BUCKETS - 1) {
1280 mFrameBuckets[numPeriods] += elapsedTime;
1281 } else {
1282 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1283 }
1284 mTotalTime += elapsedTime;
1285 }
1286 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001287}
1288
1289void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001290 ATRACE_CALL();
1291 ALOGV("rebuildLayerStacks");
1292
Mathias Agopiancd60f992012-08-16 16:28:27 -07001293 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001294 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001295 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001296 mVisibleRegionsDirty = false;
1297 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001298
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001299 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001300 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001301 Region opaqueRegion;
1302 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001303 Vector<sp<Layer>> layersSortedByZ;
1304 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1305 const Transform& tr(displayDevice->getTransform());
1306 const Rect bounds(displayDevice->getBounds());
1307 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001308 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001309 displayDevice->getLayerStack(), dirtyRegion,
1310 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001311
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001312 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001313 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001314 const sp<Layer>& layer(layers[i]);
1315 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001316 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001317 Region drawRegion(tr.transform(
1318 layer->visibleNonTransparentRegion));
1319 drawRegion.andSelf(bounds);
1320 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001321 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001322 } else {
1323 // Clear out the HWC layer if this layer was
1324 // previously visible, but no longer is
1325 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1326 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001327 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001328 }
1329 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001330 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001331 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1332 displayDevice->undefinedRegion.set(bounds);
1333 displayDevice->undefinedRegion.subtractSelf(
1334 tr.transform(opaqueRegion));
1335 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001336 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001337 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001338}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001339
Mathias Agopiancd60f992012-08-16 16:28:27 -07001340void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001341 ATRACE_CALL();
1342 ALOGV("setUpHWComposer");
1343
Jesse Hall028dc8f2013-08-20 16:35:32 -07001344 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001345 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1346 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1347 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1348
1349 // If nothing has changed (!dirty), don't recompose.
1350 // If something changed, but we don't currently have any visible layers,
1351 // and didn't when we last did a composition, then skip it this time.
1352 // The second rule does two things:
1353 // - When all layers are removed from a display, we'll emit one black
1354 // frame, then nothing more until we get new layers.
1355 // - When a display is created with a private layer stack, we won't
1356 // emit any black frames until a layer is added to the layer stack.
1357 bool mustRecompose = dirty && !(empty && wasEmpty);
1358
1359 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1360 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1361 mustRecompose ? "doing" : "skipping",
1362 dirty ? "+" : "-",
1363 empty ? "+" : "-",
1364 wasEmpty ? "+" : "-");
1365
Dan Stoza71433162014-02-04 16:22:36 -08001366 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001367
1368 if (mustRecompose) {
1369 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1370 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001371 }
1372
Dan Stoza9e56aa02015-11-02 13:00:03 -08001373 // build the h/w work list
1374 if (CC_UNLIKELY(mGeometryInvalid)) {
1375 mGeometryInvalid = false;
1376 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1377 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1378 const auto hwcId = displayDevice->getHwcDisplayId();
1379 if (hwcId >= 0) {
1380 const Vector<sp<Layer>>& currentLayers(
1381 displayDevice->getVisibleLayersSortedByZ());
1382 bool foundLayerWithoutHwc = false;
1383 for (auto& layer : currentLayers) {
1384 if (!layer->hasHwcLayer(hwcId)) {
1385 auto hwcLayer = mHwc->createLayer(hwcId);
1386 if (hwcLayer) {
1387 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1388 } else {
1389 layer->forceClientComposition(hwcId);
1390 foundLayerWithoutHwc = true;
1391 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001392 }
1393 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001394
Dan Stoza9e56aa02015-11-02 13:00:03 -08001395 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001396 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001397 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001398 }
1399 }
1400 }
1401 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001402 }
Riley Andrews03414a12014-07-01 14:22:59 -07001403
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001404
1405 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1406
Dan Stoza9e56aa02015-11-02 13:00:03 -08001407 // Set the per-frame data
1408 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1409 auto& displayDevice = mDisplays[displayId];
1410 const auto hwcId = displayDevice->getHwcDisplayId();
1411 if (hwcId < 0) {
1412 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001413 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001414 if (colorMatrix != mPreviousColorMatrix) {
1415 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1416 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1417 "display %zd: %d", displayId, result);
1418 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001419 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1420 layer->setPerFrameData(displayDevice);
1421 }
1422 }
1423
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001424 mPreviousColorMatrix = colorMatrix;
1425
Dan Stoza9e56aa02015-11-02 13:00:03 -08001426 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001427 auto& displayDevice = mDisplays[displayId];
1428 if (!displayDevice->isDisplayOn()) {
1429 continue;
1430 }
1431
1432 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001433 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1434 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001435 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001436}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001437
Mathias Agopiancd60f992012-08-16 16:28:27 -07001438void SurfaceFlinger::doComposition() {
1439 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001440 ALOGV("doComposition");
1441
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001442 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001443 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001444 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001445 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001446 // transform the dirty region into this screen's coordinate space
1447 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001448
1449 // repaint the framebuffer (if needed)
1450 doDisplayComposition(hw, dirtyRegion);
1451
Mathias Agopiancd60f992012-08-16 16:28:27 -07001452 hw->dirtyRegion.clear();
1453 hw->flip(hw->swapRegion);
1454 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001455 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001456 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001457 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001458}
1459
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001460void SurfaceFlinger::postFramebuffer()
1461{
Mathias Agopian841cde52012-03-01 15:44:37 -08001462 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001463 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001464
Mathias Agopiana44b0412011-10-16 18:46:35 -07001465 const nsecs_t now = systemTime();
1466 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001467
Dan Stoza9e56aa02015-11-02 13:00:03 -08001468 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1469 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001470 if (!displayDevice->isDisplayOn()) {
1471 continue;
1472 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001473 const auto hwcId = displayDevice->getHwcDisplayId();
1474 if (hwcId >= 0) {
1475 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001476 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001477 displayDevice->onSwapBuffersCompleted();
Season Lib2c838b2016-08-04 14:32:44 -07001478 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001479 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1480 sp<Fence> releaseFence = Fence::NO_FENCE;
1481 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1482 releaseFence = displayDevice->getClientTargetAcquireFence();
1483 } else {
1484 auto hwcLayer = layer->getHwcLayer(hwcId);
1485 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001486 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001487 layer->onLayerDisplayed(releaseFence);
1488 }
1489 if (hwcId >= 0) {
1490 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001491 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001492 }
1493
Mathias Agopiana44b0412011-10-16 18:46:35 -07001494 mLastSwapBufferTime = systemTime() - now;
1495 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001496
1497 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1498 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1499 logFrameStats();
1500 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001501}
1502
Mathias Agopian87baae12012-07-31 12:38:26 -07001503void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001504{
Mathias Agopian841cde52012-03-01 15:44:37 -08001505 ATRACE_CALL();
1506
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001507 // here we keep a copy of the drawing state (that is the state that's
1508 // going to be overwritten by handleTransactionLocked()) outside of
1509 // mStateLock so that the side-effects of the State assignment
1510 // don't happen with mStateLock held (which can cause deadlocks).
1511 State drawingState(mDrawingState);
1512
Mathias Agopianca4d3602011-05-19 15:38:14 -07001513 Mutex::Autolock _l(mStateLock);
1514 const nsecs_t now = systemTime();
1515 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001516
Mathias Agopianca4d3602011-05-19 15:38:14 -07001517 // Here we're guaranteed that some transaction flags are set
1518 // so we can call handleTransactionLocked() unconditionally.
1519 // We call getTransactionFlags(), which will also clear the flags,
1520 // with mStateLock held to guarantee that mCurrentState won't change
1521 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001522
Mathias Agopiane57f2922012-08-09 16:29:12 -07001523 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001524 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001525
Mathias Agopianca4d3602011-05-19 15:38:14 -07001526 mLastTransactionTime = systemTime() - now;
1527 mDebugInTransaction = 0;
1528 invalidateHwcGeometry();
1529 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001530}
1531
Mathias Agopian87baae12012-07-31 12:38:26 -07001532void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001533{
1534 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001535 const size_t count = currentLayers.size();
1536
Dan Stoza7dde5992015-05-22 09:51:44 -07001537 // Notify all layers of available frames
1538 for (size_t i = 0; i < count; ++i) {
1539 currentLayers[i]->notifyAvailableFrames();
1540 }
1541
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001542 /*
1543 * Traversal of the children
1544 * (perform the transaction for each of them if needed)
1545 */
1546
Mathias Agopian3559b072012-08-15 13:46:03 -07001547 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001548 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001549 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001550 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1551 if (!trFlags) continue;
1552
1553 const uint32_t flags = layer->doTransaction(0);
1554 if (flags & Layer::eVisibleRegion)
1555 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001556 }
1557 }
1558
1559 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001560 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001561 */
1562
Mathias Agopiane57f2922012-08-09 16:29:12 -07001563 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001564 // here we take advantage of Vector's copy-on-write semantics to
1565 // improve performance by skipping the transaction entirely when
1566 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001567 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1568 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001569 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001570 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001571 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001572 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001573
1574 // find the displays that were removed
1575 // (ie: in drawing state but not in current state)
1576 // also handle displays that changed
1577 // (ie: displays that are in both lists)
1578 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001579 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1580 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001581 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001582 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001583 // Call makeCurrent() on the primary display so we can
1584 // be sure that nothing associated with this display
1585 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001586 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001587 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001588 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1589 if (hw != NULL)
1590 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001591 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001592 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001593 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001594 } else {
1595 ALOGW("trying to remove the main display");
1596 }
1597 } else {
1598 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001599 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001600 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001601 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1602 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001603 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001604 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001605 // recreating the DisplayDevice, so we just remove it
1606 // from the drawing state, so that it get re-added
1607 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001608 sp<DisplayDevice> hw(getDisplayDevice(display));
1609 if (hw != NULL)
1610 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001611 mDisplays.removeItem(display);
1612 mDrawingState.displays.removeItemsAt(i);
1613 dc--; i--;
1614 // at this point we must loop to the next item
1615 continue;
1616 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001617
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001618 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001619 if (disp != NULL) {
1620 if (state.layerStack != draw[i].layerStack) {
1621 disp->setLayerStack(state.layerStack);
1622 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001623 if ((state.orientation != draw[i].orientation)
1624 || (state.viewport != draw[i].viewport)
1625 || (state.frame != draw[i].frame))
1626 {
1627 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001628 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001629 }
Michael Lentine47e45402014-07-18 15:34:25 -07001630 if (state.width != draw[i].width || state.height != draw[i].height) {
1631 disp->setDisplaySize(state.width, state.height);
1632 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001633 }
1634 }
1635 }
1636
1637 // find displays that were added
1638 // (ie: in current state but not in drawing state)
1639 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001640 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001641 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001642
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001643 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001644 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001645 sp<IGraphicBufferProducer> bqProducer;
1646 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001647 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1648 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001649
Dan Stoza9e56aa02015-11-02 13:00:03 -08001650 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001651 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001652 // Virtual displays without a surface are dormant:
1653 // they have external state (layer stack, projection,
1654 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001655 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001656
Dan Stoza8cf150a2016-08-02 10:27:31 -07001657 if (mUseHwcVirtualDisplays) {
1658 int width = 0;
1659 int status = state.surface->query(
1660 NATIVE_WINDOW_WIDTH, &width);
1661 ALOGE_IF(status != NO_ERROR,
1662 "Unable to query width (%d)", status);
1663 int height = 0;
1664 status = state.surface->query(
1665 NATIVE_WINDOW_HEIGHT, &height);
1666 ALOGE_IF(status != NO_ERROR,
1667 "Unable to query height (%d)", status);
1668 int intFormat = 0;
1669 status = state.surface->query(
1670 NATIVE_WINDOW_FORMAT, &intFormat);
1671 ALOGE_IF(status != NO_ERROR,
1672 "Unable to query format (%d)", status);
1673 auto format = static_cast<android_pixel_format_t>(
1674 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001675
Dan Stoza8cf150a2016-08-02 10:27:31 -07001676 mHwc->allocateVirtualDisplay(width, height, &format,
1677 &hwcId);
1678 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001679
Dan Stoza5cf424b2016-05-20 14:02:39 -07001680 // TODO: Plumb requested format back up to consumer
1681
Dan Stoza9e56aa02015-11-02 13:00:03 -08001682 sp<VirtualDisplaySurface> vds =
1683 new VirtualDisplaySurface(*mHwc,
1684 hwcId, state.surface, bqProducer,
1685 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001686
1687 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001688 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001689 }
1690 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001691 ALOGE_IF(state.surface!=NULL,
1692 "adding a supported display, but rendering "
1693 "surface is provided (%p), ignoring it",
1694 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001695 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1696 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1697 dispSurface = new FramebufferSurface(*mHwc,
1698 DisplayDevice::DISPLAY_EXTERNAL,
1699 bqConsumer);
1700 producer = bqProducer;
1701 } else {
1702 ALOGE("Attempted to add non-external non-virtual"
1703 " display");
1704 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001705 }
1706
1707 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001708 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001709 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001710 state.type, hwcId, state.isSecure, display,
1711 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001712 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001713 hw->setLayerStack(state.layerStack);
1714 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001715 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001716 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001717 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001718 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001719 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001720 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001721 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001722 }
1723 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001724 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001725 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001726
Mathias Agopian84300952012-11-21 16:02:13 -08001727 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1728 // The transform hint might have changed for some layers
1729 // (either because a display has changed, or because a layer
1730 // as changed).
1731 //
1732 // Walk through all the layers in currentLayers,
1733 // and update their transform hint.
1734 //
1735 // If a layer is visible only on a single display, then that
1736 // display is used to calculate the hint, otherwise we use the
1737 // default display.
1738 //
1739 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1740 // the hint is set before we acquire a buffer from the surface texture.
1741 //
1742 // NOTE: layer transactions have taken place already, so we use their
1743 // drawing state. However, SurfaceFlinger's own transaction has not
1744 // happened yet, so we must use the current state layer list
1745 // (soon to become the drawing state list).
1746 //
1747 sp<const DisplayDevice> disp;
1748 uint32_t currentlayerStack = 0;
1749 for (size_t i=0; i<count; i++) {
1750 // NOTE: we rely on the fact that layers are sorted by
1751 // layerStack first (so we don't have to traverse the list
1752 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001753 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001754 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001755 if (i==0 || currentlayerStack != layerStack) {
1756 currentlayerStack = layerStack;
1757 // figure out if this layerstack is mirrored
1758 // (more than one display) if so, pick the default display,
1759 // if not, pick the only display it's on.
1760 disp.clear();
1761 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1762 sp<const DisplayDevice> hw(mDisplays[dpy]);
1763 if (hw->getLayerStack() == currentlayerStack) {
1764 if (disp == NULL) {
1765 disp = hw;
1766 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001767 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001768 break;
1769 }
1770 }
1771 }
1772 }
Chet Haase91d25932013-04-11 15:24:55 -07001773 if (disp == NULL) {
1774 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1775 // redraw after transform hint changes. See bug 8508397.
1776
1777 // could be null when this layer is using a layerStack
1778 // that is not visible on any display. Also can occur at
1779 // screen off/on times.
1780 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001781 }
Chet Haase91d25932013-04-11 15:24:55 -07001782 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001783 }
1784 }
1785
1786
Mathias Agopian3559b072012-08-15 13:46:03 -07001787 /*
1788 * Perform our own transaction if needed
1789 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001790
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001791 const LayerVector& layers(mDrawingState.layersSortedByZ);
1792 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001793 // layers have been added
1794 mVisibleRegionsDirty = true;
1795 }
1796
1797 // some layers might have been removed, so
1798 // we need to update the regions they're exposing.
1799 if (mLayersRemoved) {
1800 mLayersRemoved = false;
1801 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001802 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001803 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001804 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001805 if (currentLayers.indexOf(layer) < 0) {
1806 // this layer is not visible anymore
1807 // TODO: we could traverse the tree from front to back and
1808 // compute the actual visible region
1809 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001810 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001811 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001812 Region(Rect(s.active.w, s.active.h)));
1813 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001814 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001815 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001816 }
1817
1818 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001819
1820 updateCursorAsync();
1821}
1822
1823void SurfaceFlinger::updateCursorAsync()
1824{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001825 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1826 auto& displayDevice = mDisplays[displayId];
1827 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001828 continue;
1829 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001830
1831 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1832 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001833 }
1834 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001835}
1836
1837void SurfaceFlinger::commitTransaction()
1838{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00001839 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07001840 // Notify removed layers now that they can't be drawn from
1841 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001842 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1843 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001844 mLayersPendingRemoval[i]->onRemoved();
1845 }
1846 mLayersPendingRemoval.clear();
1847 }
1848
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001849 // If this transaction is part of a window animation then the next frame
1850 // we composite should be considered an animation as well.
1851 mAnimCompositionPending = mAnimTransactionPending;
1852
Mathias Agopian4fec8732012-06-29 14:12:52 -07001853 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001854 mTransactionPending = false;
1855 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001856 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001857}
1858
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001859void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001860 const LayerVector& currentLayers, uint32_t layerStack,
1861 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001862{
Mathias Agopian841cde52012-03-01 15:44:37 -08001863 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001864 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001865
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001866 Region aboveOpaqueLayers;
1867 Region aboveCoveredLayers;
1868 Region dirty;
1869
Mathias Agopian87baae12012-07-31 12:38:26 -07001870 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001871
1872 size_t i = currentLayers.size();
1873 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001874 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001875
1876 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001877 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001878
Jesse Hall01e29052013-02-19 16:13:35 -08001879 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001880 if (s.layerStack != layerStack)
1881 continue;
1882
Mathias Agopianab028732010-03-16 16:41:46 -07001883 /*
1884 * opaqueRegion: area of a surface that is fully opaque.
1885 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001886 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001887
1888 /*
1889 * visibleRegion: area of a surface that is visible on screen
1890 * and not fully transparent. This is essentially the layer's
1891 * footprint minus the opaque regions above it.
1892 * Areas covered by a translucent surface are considered visible.
1893 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001894 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001895
1896 /*
1897 * coveredRegion: area of a surface that is covered by all
1898 * visible regions above it (which includes the translucent areas).
1899 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001900 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001901
Jesse Halla8026d22012-09-25 13:25:04 -07001902 /*
1903 * transparentRegion: area of a surface that is hinted to be completely
1904 * transparent. This is only used to tell when the layer has no visible
1905 * non-transparent regions and can be removed from the layer list. It
1906 * does not affect the visibleRegion of this layer or any layers
1907 * beneath it. The hint may not be correct if apps don't respect the
1908 * SurfaceView restrictions (which, sadly, some don't).
1909 */
1910 Region transparentRegion;
1911
Mathias Agopianab028732010-03-16 16:41:46 -07001912
1913 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001914 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001915 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001916 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001917 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001918 if (!visibleRegion.isEmpty()) {
1919 // Remove the transparent area from the visible region
1920 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001921 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001922 if (tr.preserveRects()) {
1923 // transform the transparent region
1924 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001925 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001926 // transformation too complex, can't do the
1927 // transparent region optimization.
1928 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001929 }
Mathias Agopianab028732010-03-16 16:41:46 -07001930 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001931
Mathias Agopianab028732010-03-16 16:41:46 -07001932 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001933 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001934 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001935 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1936 // the opaque region is the layer's footprint
1937 opaqueRegion = visibleRegion;
1938 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001939 }
1940 }
1941
Mathias Agopianab028732010-03-16 16:41:46 -07001942 // Clip the covered region to the visible region
1943 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1944
1945 // Update aboveCoveredLayers for next (lower) layer
1946 aboveCoveredLayers.orSelf(visibleRegion);
1947
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001948 // subtract the opaque region covered by the layers above us
1949 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001950
1951 // compute this layer's dirty region
1952 if (layer->contentDirty) {
1953 // we need to invalidate the whole region
1954 dirty = visibleRegion;
1955 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001956 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001957 layer->contentDirty = false;
1958 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001959 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001960 * the exposed region consists of two components:
1961 * 1) what's VISIBLE now and was COVERED before
1962 * 2) what's EXPOSED now less what was EXPOSED before
1963 *
1964 * note that (1) is conservative, we start with the whole
1965 * visible region but only keep what used to be covered by
1966 * something -- which mean it may have been exposed.
1967 *
1968 * (2) handles areas that were not covered by anything but got
1969 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001970 */
Mathias Agopianab028732010-03-16 16:41:46 -07001971 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001972 const Region oldVisibleRegion = layer->visibleRegion;
1973 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001974 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1975 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001976 }
1977 dirty.subtractSelf(aboveOpaqueLayers);
1978
1979 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001980 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001981
Mathias Agopianab028732010-03-16 16:41:46 -07001982 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001983 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001984
Jesse Halla8026d22012-09-25 13:25:04 -07001985 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001986 layer->setVisibleRegion(visibleRegion);
1987 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001988 layer->setVisibleNonTransparentRegion(
1989 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001990 }
1991
Mathias Agopian87baae12012-07-31 12:38:26 -07001992 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001993}
1994
Mathias Agopian87baae12012-07-31 12:38:26 -07001995void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1996 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001997 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001998 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1999 if (hw->getLayerStack() == layerStack) {
2000 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002001 }
2002 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002003}
2004
Dan Stoza6b9454d2014-11-07 16:00:59 -08002005bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002006{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 ALOGV("handlePageFlip");
2008
Mathias Agopian4fec8732012-06-29 14:12:52 -07002009 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010
Mathias Agopian4fec8732012-06-29 14:12:52 -07002011 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002012 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002013 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002014
2015 // Store the set of layers that need updates. This set must not change as
2016 // buffers are being latched, as this could result in a deadlock.
2017 // Example: Two producers share the same command stream and:
2018 // 1.) Layer 0 is latched
2019 // 2.) Layer 0 gets a new frame
2020 // 2.) Layer 1 gets a new frame
2021 // 3.) Layer 1 is latched.
2022 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2023 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002024 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002025 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002026 if (layer->hasQueuedFrame()) {
2027 frameQueued = true;
2028 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002029 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002030 } else {
2031 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002032 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002033 } else {
2034 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002035 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002036 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002037 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07002038 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07002039 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002040 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002041 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002042 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002043
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002044 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002045
2046 // If we will need to wake up at some time in the future to deal with a
2047 // queued frame that shouldn't be displayed during this vsync period, wake
2048 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002049 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002050 signalLayerUpdate();
2051 }
2052
2053 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055}
2056
Mathias Agopianad456f92011-01-13 17:53:01 -08002057void SurfaceFlinger::invalidateHwcGeometry()
2058{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002060}
2061
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002062
Mathias Agopiancd60f992012-08-16 16:28:27 -07002063void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002064 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002065{
Dan Stoza71433162014-02-04 16:22:36 -08002066 // We only need to actually compose the display if:
2067 // 1) It is being handled by hardware composer, which may need this to
2068 // keep its virtual display state machine in sync, or
2069 // 2) There is work to be done (the dirty region isn't empty)
2070 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2071 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002073 return;
2074 }
2075
Dan Stoza9e56aa02015-11-02 13:00:03 -08002076 ALOGV("doDisplayComposition");
2077
Mathias Agopian87baae12012-07-31 12:38:26 -07002078 Region dirtyRegion(inDirtyRegion);
2079
Mathias Agopianb8a55602009-06-26 19:06:36 -07002080 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002081 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002082
Mathias Agopian42977342012-08-05 00:40:46 -07002083 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002084 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002085 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2086 // takes a rectangle, we must make sure to update that whole
2087 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002088 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002089 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002090 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002091 // We need to redraw the rectangle that will be updated
2092 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002093 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002094 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002095 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002096 } else {
2097 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002098 dirtyRegion.set(hw->bounds());
2099 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002100 }
2101 }
2102
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002103 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002105 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002106 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002107
2108 // swap buffers (presentation)
2109 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002110}
2111
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112bool SurfaceFlinger::doComposeSurfaces(
2113 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002114{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002116
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002118
2119 mat4 oldColorMatrix;
2120 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2121 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2122 if (applyColorMatrix) {
2123 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2124 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2125 }
2126
Dan Stoza9e56aa02015-11-02 13:00:03 -08002127 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2128 if (hasClientComposition) {
2129 ALOGV("hasClientComposition");
2130
2131 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002132 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002134 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2135 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2136 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2137 }
2138 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002139 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002140
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002141 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002142 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2143 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002144 // when using overlays, we assume a fully transparent framebuffer
2145 // NOTE: we could reduce how much we need to clear, for instance
2146 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002147 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002148 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002149 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002150 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002151 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002153
2154 // we remove the scissor part
2155 // we're left with the letterbox region
2156 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002158
2159 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002160 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002161
2162 // but limit it to the dirty region
2163 region.andSelf(dirty);
2164
Mathias Agopianb9494d52012-04-18 02:28:45 -07002165 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002166 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002167 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002168 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002169 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002170 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002171
Dan Stoza9e56aa02015-11-02 13:00:03 -08002172 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002173 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002174 // scissor on the main display. It should never be needed
2175 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 const Rect& bounds(displayDevice->getBounds());
2177 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002178 if (scissor != bounds) {
2179 // scissor doesn't match the screen's dimensions, so we
2180 // need to clear everything outside of it and enable
2181 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002182
Mathias Agopianf45c5102012-10-24 16:29:17 -07002183 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 const uint32_t height = displayDevice->getHeight();
2185 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002186 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002187 }
2188 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002189 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002190
Mathias Agopian85d751c2012-08-29 16:59:24 -07002191 /*
2192 * and then, render the layers targeted at the framebuffer
2193 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002194
Dan Stoza9e56aa02015-11-02 13:00:03 -08002195 ALOGV("Rendering client layers");
2196 const Transform& displayTransform = displayDevice->getTransform();
2197 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002198 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002199 bool firstLayer = true;
2200 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2201 const Region clip(dirty.intersect(
2202 displayTransform.transform(layer->visibleRegion)));
2203 ALOGV("Layer: %s", layer->getName().string());
2204 ALOGV(" Composition type: %s",
2205 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002206 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002207 switch (layer->getCompositionType(hwcId)) {
2208 case HWC2::Composition::Cursor:
2209 case HWC2::Composition::Device:
2210 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002211 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002212 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2213 layer->isOpaque(state) && (state.alpha == 1.0f)
2214 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002215 // never clear the very first layer since we're
2216 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002217 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002218 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002219 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002220 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002221 case HWC2::Composition::Client: {
2222 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002223 break;
2224 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002226 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002227 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 } else {
2229 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002230 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002231 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002232 }
2233 } else {
2234 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002235 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002236 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002237 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002238 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002239 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002240 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002241 }
2242 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002243
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002244 if (applyColorMatrix) {
2245 getRenderEngine().setupColorTransform(oldColorMatrix);
2246 }
2247
Mathias Agopianf45c5102012-10-24 16:29:17 -07002248 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002249 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002250 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002251}
2252
Mathias Agopian3f844832013-08-07 21:24:32 -07002253void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002254 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002255 RenderEngine& engine(getRenderEngine());
2256 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002257}
2258
Dan Stoza7d89d062015-04-30 13:29:25 -07002259status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002260 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002261 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002262 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002263{
Dan Stoza7d89d062015-04-30 13:29:25 -07002264 // add this layer to the current state list
2265 {
2266 Mutex::Autolock _l(mStateLock);
2267 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2268 return NO_MEMORY;
2269 }
2270 mCurrentState.layersSortedByZ.add(lbc);
2271 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2272 }
2273
Mathias Agopian96f08192010-06-02 23:28:45 -07002274 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002275 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002276
Dan Stoza7d89d062015-04-30 13:29:25 -07002277 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002278}
2279
Dan Stoza22851c32016-08-09 13:21:03 -07002280status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002281 Mutex::Autolock _l(mStateLock);
Dan Stoza22851c32016-08-09 13:21:03 -07002282 sp<Layer> layer = weakLayer.promote();
2283 if (layer == nullptr) {
2284 // The layer has already been removed, carry on
2285 return NO_ERROR;
2286 }
2287
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002288 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2289 if (index >= 0) {
2290 mLayersPendingRemoval.push(layer);
2291 mLayersRemoved = true;
2292 setTransactionFlags(eTransactionNeeded);
2293 return NO_ERROR;
2294 }
2295 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296}
2297
Dan Stozac7014012014-02-14 15:03:43 -08002298uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002299 return android_atomic_release_load(&mTransactionFlags);
2300}
2301
Mathias Agopian3f844832013-08-07 21:24:32 -07002302uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2304}
2305
Mathias Agopian3f844832013-08-07 21:24:32 -07002306uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2308 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002309 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310 }
2311 return old;
2312}
2313
Mathias Agopian8b33f032012-07-24 20:43:54 -07002314void SurfaceFlinger::setTransactionState(
2315 const Vector<ComposerState>& state,
2316 const Vector<DisplayState>& displays,
2317 uint32_t flags)
2318{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002319 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002320 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002321 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002322
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002323 if (flags & eAnimation) {
2324 // For window updates that are part of an animation we must wait for
2325 // previous animation "frames" to be handled.
2326 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002327 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002328 if (CC_UNLIKELY(err != NO_ERROR)) {
2329 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002330 // caller after a few seconds.
2331 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2332 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002333 mAnimTransactionPending = false;
2334 break;
2335 }
2336 }
2337 }
2338
Mathias Agopiane57f2922012-08-09 16:29:12 -07002339 size_t count = displays.size();
2340 for (size_t i=0 ; i<count ; i++) {
2341 const DisplayState& s(displays[i]);
2342 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002343 }
2344
Mathias Agopiane57f2922012-08-09 16:29:12 -07002345 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002346 for (size_t i=0 ; i<count ; i++) {
2347 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002348 // Here we need to check that the interface we're given is indeed
2349 // one of our own. A malicious client could give us a NULL
2350 // IInterface, or one of its own or even one of our own but a
2351 // different type. All these situations would cause us to crash.
2352 //
2353 // NOTE: it would be better to use RTTI as we could directly check
2354 // that we have a Client*. however, RTTI is disabled in Android.
2355 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002356 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002357 if (binder != NULL) {
2358 String16 desc(binder->getInterfaceDescriptor());
2359 if (desc == ISurfaceComposerClient::descriptor) {
2360 sp<Client> client( static_cast<Client *>(s.client.get()) );
2361 transactionFlags |= setClientStateLocked(client, s.state);
2362 }
2363 }
2364 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002365 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002366
Robert Carr2a7dbb42016-05-24 11:41:28 -07002367 // If a synchronous transaction is explicitly requested without any changes,
2368 // force a transaction anyway. This can be used as a flush mechanism for
2369 // previous async transactions.
2370 if (transactionFlags == 0 && (flags & eSynchronous)) {
2371 transactionFlags = eTransactionNeeded;
2372 }
2373
Mathias Agopian386aa982011-11-07 21:58:03 -08002374 if (transactionFlags) {
Irvelffc9efc2016-07-27 15:16:37 -07002375 if (mInterceptor.isEnabled()) {
2376 mInterceptor.saveTransaction(state, mCurrentState.displays, displays, flags);
2377 }
Irvel468051e2016-06-13 16:44:44 -07002378
Mathias Agopian386aa982011-11-07 21:58:03 -08002379 // this triggers the transaction
2380 setTransactionFlags(transactionFlags);
2381
2382 // if this is a synchronous transaction, wait for it to take effect
2383 // before returning.
2384 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002385 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002386 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002387 if (flags & eAnimation) {
2388 mAnimTransactionPending = true;
2389 }
2390 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002391 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2392 if (CC_UNLIKELY(err != NO_ERROR)) {
2393 // just in case something goes wrong in SF, return to the
2394 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002395 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2396 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002397 break;
2398 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002399 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 }
2401}
2402
Mathias Agopiane57f2922012-08-09 16:29:12 -07002403uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2404{
Jesse Hall9a143922012-10-04 16:29:19 -07002405 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2406 if (dpyIdx < 0)
2407 return 0;
2408
Mathias Agopiane57f2922012-08-09 16:29:12 -07002409 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002410 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002411 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002412 const uint32_t what = s.what;
2413 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002414 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002415 disp.surface = s.surface;
2416 flags |= eDisplayTransactionNeeded;
2417 }
2418 }
2419 if (what & DisplayState::eLayerStackChanged) {
2420 if (disp.layerStack != s.layerStack) {
2421 disp.layerStack = s.layerStack;
2422 flags |= eDisplayTransactionNeeded;
2423 }
2424 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002425 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002426 if (disp.orientation != s.orientation) {
2427 disp.orientation = s.orientation;
2428 flags |= eDisplayTransactionNeeded;
2429 }
2430 if (disp.frame != s.frame) {
2431 disp.frame = s.frame;
2432 flags |= eDisplayTransactionNeeded;
2433 }
2434 if (disp.viewport != s.viewport) {
2435 disp.viewport = s.viewport;
2436 flags |= eDisplayTransactionNeeded;
2437 }
2438 }
Michael Lentine47e45402014-07-18 15:34:25 -07002439 if (what & DisplayState::eDisplaySizeChanged) {
2440 if (disp.width != s.width) {
2441 disp.width = s.width;
2442 flags |= eDisplayTransactionNeeded;
2443 }
2444 if (disp.height != s.height) {
2445 disp.height = s.height;
2446 flags |= eDisplayTransactionNeeded;
2447 }
2448 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002449 }
2450 return flags;
2451}
2452
2453uint32_t SurfaceFlinger::setClientStateLocked(
2454 const sp<Client>& client,
2455 const layer_state_t& s)
2456{
2457 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002458 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002459 if (layer != 0) {
2460 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002461 bool geometryAppliesWithResize =
2462 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002463 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002464 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002465 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002466 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002467 }
2468 if (what & layer_state_t::eLayerChanged) {
2469 // NOTE: index needs to be calculated before we update the state
2470 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002471 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002472 mCurrentState.layersSortedByZ.removeAt(idx);
2473 mCurrentState.layersSortedByZ.add(layer);
2474 // we need traversal (state changed)
2475 // AND transaction (list changed)
2476 flags |= eTransactionNeeded|eTraversalNeeded;
2477 }
2478 }
2479 if (what & layer_state_t::eSizeChanged) {
2480 if (layer->setSize(s.w, s.h)) {
2481 flags |= eTraversalNeeded;
2482 }
2483 }
2484 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002485 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002486 flags |= eTraversalNeeded;
2487 }
2488 if (what & layer_state_t::eMatrixChanged) {
2489 if (layer->setMatrix(s.matrix))
2490 flags |= eTraversalNeeded;
2491 }
2492 if (what & layer_state_t::eTransparentRegionChanged) {
2493 if (layer->setTransparentRegionHint(s.transparentRegion))
2494 flags |= eTraversalNeeded;
2495 }
Dan Stoza23116082015-06-18 14:58:39 -07002496 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002497 if (layer->setFlags(s.flags, s.mask))
2498 flags |= eTraversalNeeded;
2499 }
2500 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002501 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002502 flags |= eTraversalNeeded;
2503 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002504 if (what & layer_state_t::eFinalCropChanged) {
2505 if (layer->setFinalCrop(s.finalCrop))
2506 flags |= eTraversalNeeded;
2507 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002508 if (what & layer_state_t::eLayerStackChanged) {
2509 // NOTE: index needs to be calculated before we update the state
2510 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002511 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002512 mCurrentState.layersSortedByZ.removeAt(idx);
2513 mCurrentState.layersSortedByZ.add(layer);
2514 // we need traversal (state changed)
2515 // AND transaction (list changed)
2516 flags |= eTransactionNeeded|eTraversalNeeded;
2517 }
2518 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002519 if (what & layer_state_t::eDeferTransaction) {
2520 layer->deferTransactionUntil(s.handle, s.frameNumber);
2521 // We don't trigger a traversal here because if no other state is
2522 // changed, we don't want this to cause any more work
2523 }
Robert Carrc3574f72016-03-24 12:19:32 -07002524 if (what & layer_state_t::eOverrideScalingModeChanged) {
2525 layer->setOverrideScalingMode(s.overrideScalingMode);
2526 // We don't trigger a traversal here because if no other state is
2527 // changed, we don't want this to cause any more work
2528 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002529 }
2530 return flags;
2531}
2532
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002533status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002534 const String8& name,
2535 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002536 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2537 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002538{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002539 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002540 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002541 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002542 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002543 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002544
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002545 status_t result = NO_ERROR;
2546
2547 sp<Layer> layer;
2548
Mathias Agopian3165cc22012-08-08 19:42:09 -07002549 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2550 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002551 result = createNormalLayer(client,
2552 name, w, h, flags, format,
2553 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002554 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002555 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002556 result = createDimLayer(client,
2557 name, w, h, flags,
2558 handle, gbp, &layer);
2559 break;
2560 default:
2561 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002562 break;
2563 }
2564
Dan Stoza7d89d062015-04-30 13:29:25 -07002565 if (result != NO_ERROR) {
2566 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002567 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002568
2569 result = addClientLayer(client, *handle, *gbp, layer);
2570 if (result != NO_ERROR) {
2571 return result;
2572 }
Irvelffc9efc2016-07-27 15:16:37 -07002573 mInterceptor.saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002574
2575 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002576 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002577}
2578
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002579status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2580 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2581 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582{
2583 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002584 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002585 case PIXEL_FORMAT_TRANSPARENT:
2586 case PIXEL_FORMAT_TRANSLUCENT:
2587 format = PIXEL_FORMAT_RGBA_8888;
2588 break;
2589 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002590 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 break;
2592 }
2593
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002594 *outLayer = new Layer(this, client, name, w, h, flags);
2595 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2596 if (err == NO_ERROR) {
2597 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002598 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002600
2601 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2602 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603}
2604
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002605status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2606 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2607 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002608{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002609 *outLayer = new LayerDim(this, client, name, w, h, flags);
2610 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002611 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002612 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002613}
2614
Mathias Agopianac9fa422013-02-11 16:40:36 -08002615status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002616{
Mathias Agopian67106042013-03-14 19:18:13 -07002617 // called by the window manager when it wants to remove a Layer
2618 status_t err = NO_ERROR;
2619 sp<Layer> l(client->getLayerUser(handle));
2620 if (l != NULL) {
Irvelffc9efc2016-07-27 15:16:37 -07002621 mInterceptor.saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002622 err = removeLayer(l);
2623 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2624 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002625 }
2626 return err;
2627}
2628
Mathias Agopian13127d82013-03-05 17:47:11 -08002629status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002630{
Mathias Agopian67106042013-03-14 19:18:13 -07002631 // called by ~LayerCleaner() when all references to the IBinder (handle)
2632 // are gone
Dan Stoza22851c32016-08-09 13:21:03 -07002633 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002634}
2635
Mathias Agopianb60314a2012-04-10 22:09:54 -07002636// ---------------------------------------------------------------------------
2637
Andy McFadden13a082e2012-08-24 10:16:42 -07002638void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002639 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002640 Vector<ComposerState> state;
2641 Vector<DisplayState> displays;
2642 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002643 d.what = DisplayState::eDisplayProjectionChanged |
2644 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002645 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002646 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002647 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002648 d.frame.makeInvalid();
2649 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002650 d.width = 0;
2651 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002652 displays.add(d);
2653 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002654 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002655
Dan Stoza9e56aa02015-11-02 13:00:03 -08002656 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2657 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002658 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002659}
2660
2661void SurfaceFlinger::initializeDisplays() {
2662 class MessageScreenInitialized : public MessageBase {
2663 SurfaceFlinger* flinger;
2664 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002665 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002666 virtual bool handler() {
2667 flinger->onInitializeDisplays();
2668 return true;
2669 }
2670 };
2671 sp<MessageBase> msg = new MessageScreenInitialized(this);
2672 postMessageAsync(msg); // we may be called from main thread, use async message
2673}
2674
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002675void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2676 int mode) {
2677 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2678 this);
2679 int32_t type = hw->getDisplayType();
2680 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002681
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002682 if (mode == currentMode) {
2683 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002684 return;
2685 }
2686
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002687 hw->setPowerMode(mode);
2688 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2689 ALOGW("Trying to set power mode for virtual display");
2690 return;
2691 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002692
Irvelffc9efc2016-07-27 15:16:37 -07002693 if (mInterceptor.isEnabled()) {
2694 Mutex::Autolock _l(mStateLock);
2695 ssize_t idx = mCurrentState.displays.indexOfKey(hw->getDisplayToken());
2696 if (idx < 0) {
2697 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
2698 return;
2699 }
2700 mInterceptor.savePowerModeUpdate(mCurrentState.displays.valueAt(idx).displayId, mode);
2701 }
2702
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002703 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002704 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002705 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002706 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2707 // FIXME: eventthread only knows about the main display right now
2708 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002709 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002710 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002711
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002712 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002713 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002714 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002715
2716 struct sched_param param = {0};
2717 param.sched_priority = 1;
2718 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2719 ALOGW("Couldn't set SCHED_FIFO on display on");
2720 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002721 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002722 // Turn off the display
2723 struct sched_param param = {0};
2724 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2725 ALOGW("Couldn't set SCHED_OTHER on display off");
2726 }
2727
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002728 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002729 disableHardwareVsync(true); // also cancels any in-progress resync
2730
Mathias Agopiancde87a32012-09-13 14:09:01 -07002731 // FIXME: eventthread only knows about the main display right now
2732 mEventThread->onScreenReleased();
2733 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002734
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002735 getHwComposer().setPowerMode(type, mode);
2736 mVisibleRegionsDirty = true;
2737 // from this point on, SF will stop drawing on this display
2738 } else {
2739 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002740 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002741}
2742
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002743void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2744 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002745 SurfaceFlinger& mFlinger;
2746 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002747 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002748 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002749 MessageSetPowerMode(SurfaceFlinger& flinger,
2750 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2751 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002752 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002753 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002754 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002755 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002756 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002757 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002758 ALOGW("Attempt to set power mode = %d for virtual display",
2759 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002760 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002761 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002762 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002763 return true;
2764 }
2765 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002766 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002767 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002768}
2769
2770// ---------------------------------------------------------------------------
2771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002772status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2773{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002774 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002775
Mathias Agopianbd115332013-04-18 16:41:04 -07002776 IPCThreadState* ipc = IPCThreadState::self();
2777 const int pid = ipc->getCallingPid();
2778 const int uid = ipc->getCallingUid();
2779 if ((uid != AID_SHELL) &&
2780 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002781 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002782 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002783 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002784 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002785 // (this would indicate SF is stuck, but we want to be able to
2786 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002787 status_t err = mStateLock.timedLock(s2ns(1));
2788 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002789 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002790 result.appendFormat(
2791 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2792 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002793 }
2794
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002795 bool dumpAll = true;
2796 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002797 size_t numArgs = args.size();
2798 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002799 if ((index < numArgs) &&
2800 (args[index] == String16("--list"))) {
2801 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002802 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002803 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002804 }
2805
2806 if ((index < numArgs) &&
2807 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002808 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002809 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002810 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002811 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002812
2813 if ((index < numArgs) &&
2814 (args[index] == String16("--latency-clear"))) {
2815 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002816 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002817 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002818 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002819
2820 if ((index < numArgs) &&
2821 (args[index] == String16("--dispsync"))) {
2822 index++;
2823 mPrimaryDispSync.dump(result);
2824 dumpAll = false;
2825 }
Dan Stozab90cf072015-03-05 11:05:59 -08002826
2827 if ((index < numArgs) &&
2828 (args[index] == String16("--static-screen"))) {
2829 index++;
2830 dumpStaticScreenStats(result);
2831 dumpAll = false;
2832 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002833
2834 if ((index < numArgs) &&
2835 (args[index] == String16("--fences"))) {
2836 index++;
2837 mFenceTracker.dump(&result);
2838 dumpAll = false;
2839 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002841
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002842 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002843 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002844 }
2845
Mathias Agopian9795c422009-08-26 16:36:26 -07002846 if (locked) {
2847 mStateLock.unlock();
2848 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002849 }
2850 write(fd, result.string(), result.size());
2851 return NO_ERROR;
2852}
2853
Dan Stozac7014012014-02-14 15:03:43 -08002854void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2855 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002856{
2857 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2858 const size_t count = currentLayers.size();
2859 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002860 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002861 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002862 }
2863}
2864
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002865void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002866 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002867{
2868 String8 name;
2869 if (index < args.size()) {
2870 name = String8(args[index]);
2871 index++;
2872 }
2873
Dan Stoza9e56aa02015-11-02 13:00:03 -08002874 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2875 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002876 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002877
2878 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002879 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002880 } else {
2881 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2882 const size_t count = currentLayers.size();
2883 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002884 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002885 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002886 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002887 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002888 }
2889 }
2890}
2891
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002892void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002893 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002894{
2895 String8 name;
2896 if (index < args.size()) {
2897 name = String8(args[index]);
2898 index++;
2899 }
2900
2901 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2902 const size_t count = currentLayers.size();
2903 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002904 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002905 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002906 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002907 }
2908 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002909
Svetoslavd85084b2014-03-20 10:28:31 -07002910 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002911}
2912
Jamie Gennis6547ff42013-07-16 20:12:42 -07002913// This should only be called from the main thread. Otherwise it would need
2914// the lock and should use mCurrentState rather than mDrawingState.
2915void SurfaceFlinger::logFrameStats() {
2916 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2917 const size_t count = drawingLayers.size();
2918 for (size_t i=0 ; i<count ; i++) {
2919 const sp<Layer>& layer(drawingLayers[i]);
2920 layer->logFrameStats();
2921 }
2922
2923 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2924}
2925
Andy McFadden4803b742012-09-24 19:07:20 -07002926/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2927{
2928 static const char* config =
2929 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002930#ifdef HAS_CONTEXT_PRIORITY
2931 " HAS_CONTEXT_PRIORITY"
2932#endif
2933#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2934 " NEVER_DEFAULT_TO_ASYNC_MODE"
2935#endif
2936#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2937 " TARGET_DISABLE_TRIPLE_BUFFERING"
2938#endif
2939 "]";
2940 result.append(config);
2941}
2942
Dan Stozab90cf072015-03-05 11:05:59 -08002943void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2944{
2945 result.appendFormat("Static screen stats:\n");
2946 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2947 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2948 float percent = 100.0f *
2949 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2950 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2951 b + 1, bucketTimeSec, percent);
2952 }
2953 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2954 float percent = 100.0f *
2955 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2956 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2957 NUM_BUCKETS - 1, bucketTimeSec, percent);
2958}
2959
Dan Stozae77c7662016-05-13 11:37:28 -07002960void SurfaceFlinger::recordBufferingStats(const char* layerName,
2961 std::vector<OccupancyTracker::Segment>&& history) {
2962 Mutex::Autolock lock(mBufferingStatsMutex);
2963 auto& stats = mBufferingStats[layerName];
2964 for (const auto& segment : history) {
2965 if (!segment.usedThirdBuffer) {
2966 stats.twoBufferTime += segment.totalTime;
2967 }
2968 if (segment.occupancyAverage < 1.0f) {
2969 stats.doubleBufferedTime += segment.totalTime;
2970 } else if (segment.occupancyAverage < 2.0f) {
2971 stats.tripleBufferedTime += segment.totalTime;
2972 }
2973 ++stats.numSegments;
2974 stats.totalTime += segment.totalTime;
2975 }
2976}
2977
2978void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2979 result.append("Buffering stats:\n");
2980 result.append(" [Layer name] <Active time> <Two buffer> "
2981 "<Double buffered> <Triple buffered>\n");
2982 Mutex::Autolock lock(mBufferingStatsMutex);
2983 typedef std::tuple<std::string, float, float, float> BufferTuple;
2984 std::map<float, BufferTuple, std::greater<float>> sorted;
2985 for (const auto& statsPair : mBufferingStats) {
2986 const char* name = statsPair.first.c_str();
2987 const BufferingStats& stats = statsPair.second;
2988 if (stats.numSegments == 0) {
2989 continue;
2990 }
2991 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2992 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2993 stats.totalTime;
2994 float doubleBufferRatio = static_cast<float>(
2995 stats.doubleBufferedTime) / stats.totalTime;
2996 float tripleBufferRatio = static_cast<float>(
2997 stats.tripleBufferedTime) / stats.totalTime;
2998 sorted.insert({activeTime, {name, twoBufferRatio,
2999 doubleBufferRatio, tripleBufferRatio}});
3000 }
3001 for (const auto& sortedPair : sorted) {
3002 float activeTime = sortedPair.first;
3003 const BufferTuple& values = sortedPair.second;
3004 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
3005 std::get<0>(values).c_str(), activeTime,
3006 std::get<1>(values), std::get<2>(values),
3007 std::get<3>(values));
3008 }
3009 result.append("\n");
3010}
3011
3012
Mathias Agopian74d211a2013-04-22 16:55:35 +02003013void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
3014 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003015{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003016 bool colorize = false;
3017 if (index < args.size()
3018 && (args[index] == String16("--color"))) {
3019 colorize = true;
3020 index++;
3021 }
3022
3023 Colorizer colorizer(colorize);
3024
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003025 // figure out if we're stuck somewhere
3026 const nsecs_t now = systemTime();
3027 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3028 const nsecs_t inTransaction(mDebugInTransaction);
3029 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3030 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3031
3032 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003033 * Dump library configuration.
3034 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003035
3036 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003037 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003038 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003039 appendSfConfigString(result);
3040 appendUiConfigString(result);
3041 appendGuiConfigString(result);
3042 result.append("\n");
3043
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003044 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003045 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003046 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003047 result.append(SyncFeatures::getInstance().toString());
3048 result.append("\n");
3049
Dan Stoza9e56aa02015-11-02 13:00:03 -08003050 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3051
Andy McFadden41d67d72014-04-25 16:58:34 -07003052 colorizer.bold(result);
3053 result.append("DispSync configuration: ");
3054 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003055 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3056 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3058 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003059 result.append("\n");
3060
Dan Stozab90cf072015-03-05 11:05:59 -08003061 // Dump static screen stats
3062 result.append("\n");
3063 dumpStaticScreenStats(result);
3064 result.append("\n");
3065
Dan Stozae77c7662016-05-13 11:37:28 -07003066 dumpBufferingStats(result);
3067
Andy McFadden4803b742012-09-24 19:07:20 -07003068 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003069 * Dump the visible layer list
3070 */
3071 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3072 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003073 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003074 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003075 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003076 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003077 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003078 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003079 }
3080
3081 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003082 * Dump Display state
3083 */
3084
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003085 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003086 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003087 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003088 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3089 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003090 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003091 }
3092
3093 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003094 * Dump SurfaceFlinger global state
3095 */
3096
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003097 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003098 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003099 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003100
Mathias Agopian888c8222012-08-04 21:10:38 -07003101 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003102 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003103
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003104 colorizer.bold(result);
3105 result.appendFormat("EGL implementation : %s\n",
3106 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3107 colorizer.reset(result);
3108 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003109 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003110
Mathias Agopian875d8e12013-06-07 15:35:48 -07003111 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003112
Mathias Agopian42977342012-08-05 00:40:46 -07003113 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003114 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3115 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003116 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003117 " last eglSwapBuffers() time: %f us\n"
3118 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003119 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003120 " refresh-rate : %f fps\n"
3121 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003122 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003123 " gpu_to_cpu_unsupported : %d\n"
3124 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003125 mLastSwapBufferTime/1000.0,
3126 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003127 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003128 1e9 / activeConfig->getVsyncPeriod(),
3129 activeConfig->getDpiX(),
3130 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003131 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003132
Mathias Agopian74d211a2013-04-22 16:55:35 +02003133 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003134 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003135
Mathias Agopian74d211a2013-04-22 16:55:35 +02003136 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003137 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003138
3139 /*
3140 * VSYNC state
3141 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003142 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003143 result.append("\n");
3144
3145 /*
3146 * HWC layer minidump
3147 */
3148 for (size_t d = 0; d < mDisplays.size(); d++) {
3149 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3150 int32_t hwcId = displayDevice->getHwcDisplayId();
3151 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3152 continue;
3153 }
3154
3155 result.appendFormat("Display %d HWC layers:\n", hwcId);
3156 Layer::miniDumpHeader(result);
3157 for (size_t l = 0; l < count; l++) {
3158 const sp<Layer>& layer(currentLayers[l]);
3159 layer->miniDump(result, hwcId);
3160 }
3161 result.append("\n");
3162 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003163
3164 /*
3165 * Dump HWComposer state
3166 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003167 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003168 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003169 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003170 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003171 result.appendFormat(" h/w composer %s\n",
3172 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003173 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003174
3175 /*
3176 * Dump gralloc state
3177 */
3178 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3179 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003180}
3181
Mathias Agopian13127d82013-03-05 17:47:11 -08003182const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003183SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003184 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003185 wp<IBinder> dpy;
3186 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3187 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3188 dpy = mDisplays.keyAt(i);
3189 break;
3190 }
3191 }
3192 if (dpy == NULL) {
3193 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3194 // Just use the primary display so we have something to return
3195 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3196 }
3197 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003198}
3199
Keun young Park63f165f2012-08-31 10:53:36 -07003200bool SurfaceFlinger::startDdmConnection()
3201{
3202 void* libddmconnection_dso =
3203 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3204 if (!libddmconnection_dso) {
3205 return false;
3206 }
3207 void (*DdmConnection_start)(const char* name);
3208 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003209 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003210 if (!DdmConnection_start) {
3211 dlclose(libddmconnection_dso);
3212 return false;
3213 }
3214 (*DdmConnection_start)(getServiceName());
3215 return true;
3216}
3217
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003218status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003219 switch (code) {
3220 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003221 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003222 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003224 case CLEAR_ANIMATION_FRAME_STATS:
3225 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003226 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003227 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228 {
3229 // codes that require permission check
3230 IPCThreadState* ipc = IPCThreadState::self();
3231 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003232 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003233 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003234 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003235 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
Mathias Agopian375f5632009-06-15 18:24:59 -07003236 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003237 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003238 break;
3239 }
3240 case CAPTURE_SCREEN:
3241 {
3242 // codes that require permission check
3243 IPCThreadState* ipc = IPCThreadState::self();
3244 const int pid = ipc->getCallingPid();
3245 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003246 if ((uid != AID_GRAPHICS) &&
3247 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003248 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003249 return PERMISSION_DENIED;
3250 }
3251 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003252 }
3253 }
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07003254 return OK;
3255}
3256
3257status_t SurfaceFlinger::onTransact(
3258 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3259{
3260 status_t credentialCheck = CheckTransactCodeCredentials(code);
3261 if (credentialCheck != OK) {
3262 return credentialCheck;
3263 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003264
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3266 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003267 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003268 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003269 IPCThreadState* ipc = IPCThreadState::self();
3270 const int pid = ipc->getCallingPid();
3271 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003272 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003273 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003274 return PERMISSION_DENIED;
3275 }
3276 int n;
3277 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003278 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003279 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003280 return NO_ERROR;
3281 case 1002: // SHOW_UPDATES
3282 n = data.readInt32();
3283 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003284 invalidateHwcGeometry();
3285 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003286 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003287 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003288 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003289 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003290 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003291 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292 setTransactionFlags(
3293 eTransactionNeeded|
3294 eDisplayTransactionNeeded|
3295 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003296 return NO_ERROR;
3297 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003298 case 1006:{ // send empty update
3299 signalRefresh();
3300 return NO_ERROR;
3301 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003302 case 1008: // toggle use of hw composer
3303 n = data.readInt32();
3304 mDebugDisableHWC = n ? 1 : 0;
3305 invalidateHwcGeometry();
3306 repaintEverything();
3307 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003308 case 1009: // toggle use of transform hint
3309 n = data.readInt32();
3310 mDebugDisableTransformHint = n ? 1 : 0;
3311 invalidateHwcGeometry();
3312 repaintEverything();
3313 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003314 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003315 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316 reply->writeInt32(0);
3317 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003318 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003319 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003320 return NO_ERROR;
3321 case 1013: {
3322 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003323 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3324 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003325 return NO_ERROR;
3326 }
3327 case 1014: {
3328 // daltonize
3329 n = data.readInt32();
3330 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003331 case 1:
3332 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3333 break;
3334 case 2:
3335 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3336 break;
3337 case 3:
3338 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3339 break;
3340 default:
3341 mDaltonizer.setType(ColorBlindnessType::None);
3342 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003343 }
3344 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003345 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003346 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003347 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003348 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003349 invalidateHwcGeometry();
3350 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003351 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003352 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003353 case 1015: {
3354 // apply a color matrix
3355 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003356 if (n) {
3357 // color matrix is sent as mat3 matrix followed by vec3
3358 // offset, then packed into a mat4 where the last row is
3359 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003360 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003361 for (size_t j = 0; j < 4; j++) {
3362 mColorMatrix[i][j] = data.readFloat();
3363 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003364 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003365 } else {
3366 mColorMatrix = mat4();
3367 }
3368 invalidateHwcGeometry();
3369 repaintEverything();
3370 return NO_ERROR;
3371 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003372 // This is an experimental interface
3373 // Needs to be shifted to proper binder interface when we productize
3374 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003375 n = data.readInt32();
3376 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003377 return NO_ERROR;
3378 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003379 case 1017: {
3380 n = data.readInt32();
3381 mForceFullDamage = static_cast<bool>(n);
3382 return NO_ERROR;
3383 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003384 case 1018: { // Modify Choreographer's phase offset
3385 n = data.readInt32();
3386 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3387 return NO_ERROR;
3388 }
3389 case 1019: { // Modify SurfaceFlinger's phase offset
3390 n = data.readInt32();
3391 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3392 return NO_ERROR;
3393 }
Irvel468051e2016-06-13 16:44:44 -07003394 case 1020: { // Layer updates interceptor
3395 n = data.readInt32();
3396 if (n) {
3397 ALOGV("Interceptor enabled");
Irvelffc9efc2016-07-27 15:16:37 -07003398 mInterceptor.enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07003399 }
3400 else{
3401 ALOGV("Interceptor disabled");
3402 mInterceptor.disable();
3403 }
3404 return NO_ERROR;
3405 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07003406 case 1021: { // Disable HWC virtual displays
3407 n = data.readInt32();
3408 mUseHwcVirtualDisplays = !n;
3409 return NO_ERROR;
3410 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003411 }
3412 }
3413 return err;
3414}
3415
Mathias Agopian53331da2011-08-22 21:44:41 -07003416void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003417 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003418 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003419}
3420
Mathias Agopian59119e62010-10-11 12:37:43 -07003421// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003422// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003423// ---------------------------------------------------------------------------
3424
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003425/* The code below is here to handle b/8734824
3426 *
3427 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003428 * from the surfaceflinger thread to the calling binder thread, where they
3429 * are executed. This allows the calling thread in the calling process to be
3430 * reused and not depend on having "enough" binder threads to handle the
3431 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003432 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003433class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003434 /* Parts of GraphicProducerWrapper are run on two different threads,
3435 * communicating by sending messages via Looper but also by shared member
3436 * data. Coherence maintenance is subtle and in places implicit (ugh).
3437 *
3438 * Don't rely on Looper's sendMessage/handleMessage providing
3439 * release/acquire semantics for any data not actually in the Message.
3440 * Data going from surfaceflinger to binder threads needs to be
3441 * synchronized explicitly.
3442 *
3443 * Barrier open/wait do provide release/acquire semantics. This provides
3444 * implicit synchronization for data coming back from binder to
3445 * surfaceflinger threads.
3446 */
3447
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003448 sp<IGraphicBufferProducer> impl;
3449 sp<Looper> looper;
3450 status_t result;
3451 bool exitPending;
3452 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003453 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003454 uint32_t code;
3455 Parcel const* data;
3456 Parcel* reply;
3457
3458 enum {
3459 MSG_API_CALL,
3460 MSG_EXIT
3461 };
3462
3463 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003464 * Called on surfaceflinger thread. This is called by our "fake"
3465 * BpGraphicBufferProducer. We package the data and reply Parcel and
3466 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003467 */
3468 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003469 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003470 this->code = code;
3471 this->data = &data;
3472 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003473 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003474 // if we've exited, we run the message synchronously right here.
3475 // note (JH): as far as I can tell from looking at the code, this
3476 // never actually happens. if it does, i'm not sure if it happens
3477 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003478 handleMessage(Message(MSG_API_CALL));
3479 } else {
3480 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003481 // Prevent stores to this->{code, data, reply} from being
3482 // reordered later than the construction of Message.
3483 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003484 looper->sendMessage(this, Message(MSG_API_CALL));
3485 barrier.wait();
3486 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003487 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003488 }
3489
3490 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003491 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003492 * call the real BpGraphicBufferProducer.
3493 */
3494 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003495 int what = message.what;
3496 // Prevent reads below from happening before the read from Message
3497 atomic_thread_fence(memory_order_acquire);
3498 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003499 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003500 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003501 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003502 exitRequested = true;
3503 }
3504 }
3505
3506public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003507 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003508 : impl(impl),
3509 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003510 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003511 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003512 exitRequested(false),
3513 code(0),
3514 data(NULL),
3515 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003516 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003517
Jesse Hallb154c422014-07-13 12:47:02 -07003518 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003519 status_t waitForResponse() {
3520 do {
3521 looper->pollOnce(-1);
3522 } while (!exitRequested);
3523 return result;
3524 }
3525
Jesse Hallb154c422014-07-13 12:47:02 -07003526 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003527 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003528 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003529 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003530 // Ensure this->result is visible to the binder thread before it
3531 // handles the message.
3532 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003533 looper->sendMessage(this, Message(MSG_EXIT));
3534 }
3535};
3536
3537
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003538status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3539 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003540 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003541 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003542 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003543
3544 if (CC_UNLIKELY(display == 0))
3545 return BAD_VALUE;
3546
3547 if (CC_UNLIKELY(producer == 0))
3548 return BAD_VALUE;
3549
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003550 // if we have secure windows on this display, never allow the screen capture
3551 // unless the producer interface is local (i.e.: we can take a screenshot for
3552 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003553 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003554
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003555 // Convert to surfaceflinger's internal rotation type.
3556 Transform::orientation_flags rotationFlags;
3557 switch (rotation) {
3558 case ISurfaceComposer::eRotateNone:
3559 rotationFlags = Transform::ROT_0;
3560 break;
3561 case ISurfaceComposer::eRotate90:
3562 rotationFlags = Transform::ROT_90;
3563 break;
3564 case ISurfaceComposer::eRotate180:
3565 rotationFlags = Transform::ROT_180;
3566 break;
3567 case ISurfaceComposer::eRotate270:
3568 rotationFlags = Transform::ROT_270;
3569 break;
3570 default:
3571 rotationFlags = Transform::ROT_0;
3572 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3573 break;
3574 }
3575
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003576 class MessageCaptureScreen : public MessageBase {
3577 SurfaceFlinger* flinger;
3578 sp<IBinder> display;
3579 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003580 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003581 uint32_t reqWidth, reqHeight;
3582 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003583 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003584 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003585 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003586 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003587 public:
3588 MessageCaptureScreen(SurfaceFlinger* flinger,
3589 const sp<IBinder>& display,
3590 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003591 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003592 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003593 bool useIdentityTransform,
3594 Transform::orientation_flags rotation,
3595 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003596 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003597 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003598 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003599 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003600 rotation(rotation), result(PERMISSION_DENIED),
3601 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003602 {
3603 }
3604 status_t getResult() const {
3605 return result;
3606 }
3607 virtual bool handler() {
3608 Mutex::Autolock _l(flinger->mStateLock);
3609 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003610 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003611 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003612 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003613 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003614 return true;
3615 }
3616 };
3617
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003618 // this creates a "fake" BBinder which will serve as a "fake" remote
3619 // binder to receive the marshaled calls and forward them to the
3620 // real remote (a BpGraphicBufferProducer)
3621 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3622
3623 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3624 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003625 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003626 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003627 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003628 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003629
3630 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003631 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003632 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003633 }
3634 return res;
3635}
3636
Mathias Agopian180f10d2013-04-10 22:55:41 -07003637
3638void SurfaceFlinger::renderScreenImplLocked(
3639 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003640 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003641 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003642 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003643{
3644 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003645 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003646
3647 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003648 const int32_t hw_w = hw->getWidth();
3649 const int32_t hw_h = hw->getHeight();
3650 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003651 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003652
Dan Stozac1879002014-05-22 15:59:05 -07003653 // if a default or invalid sourceCrop is passed in, set reasonable values
3654 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3655 !sourceCrop.isValid()) {
3656 sourceCrop.setLeftTop(Point(0, 0));
3657 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3658 }
3659
3660 // ensure that sourceCrop is inside screen
3661 if (sourceCrop.left < 0) {
3662 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3663 }
Dan Stozabe31f442014-06-11 11:20:54 -07003664 if (sourceCrop.right > hw_w) {
3665 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003666 }
3667 if (sourceCrop.top < 0) {
3668 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3669 }
Dan Stozabe31f442014-06-11 11:20:54 -07003670 if (sourceCrop.bottom > hw_h) {
3671 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003672 }
3673
Mathias Agopian180f10d2013-04-10 22:55:41 -07003674 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003675 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003676
3677 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003678 engine.setViewportAndProjection(
3679 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003680 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003681
3682 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003683 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003684
3685 const LayerVector& layers( mDrawingState.layersSortedByZ );
3686 const size_t count = layers.size();
3687 for (size_t i=0 ; i<count ; ++i) {
3688 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003689 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003690 if (state.layerStack == hw->getLayerStack()) {
3691 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3692 if (layer->isVisible()) {
3693 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003694 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003695 if (filtering) layer->setFiltering(false);
3696 }
3697 }
3698 }
3699 }
3700
Mathias Agopian931bda12013-08-28 18:11:46 -07003701 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003702}
3703
3704
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003705status_t SurfaceFlinger::captureScreenImplLocked(
3706 const sp<const DisplayDevice>& hw,
3707 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003708 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003709 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003710 bool useIdentityTransform, Transform::orientation_flags rotation,
3711 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003712{
3713 ATRACE_CALL();
3714
Mathias Agopian180f10d2013-04-10 22:55:41 -07003715 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003716 uint32_t hw_w = hw->getWidth();
3717 uint32_t hw_h = hw->getHeight();
3718
3719 if (rotation & Transform::ROT_90) {
3720 std::swap(hw_w, hw_h);
3721 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003722
Mathias Agopian180f10d2013-04-10 22:55:41 -07003723 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3724 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3725 reqWidth, reqHeight, hw_w, hw_h);
3726 return BAD_VALUE;
3727 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003728
Mathias Agopian180f10d2013-04-10 22:55:41 -07003729 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3730 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3731
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003732 bool secureLayerIsVisible = false;
3733 const LayerVector& layers(mDrawingState.layersSortedByZ);
3734 const size_t count = layers.size();
3735 for (size_t i = 0 ; i < count ; ++i) {
3736 const sp<Layer>& layer(layers[i]);
3737 const Layer::State& state(layer->getDrawingState());
3738 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3739 state.z <= maxLayerZ && layer->isVisible() &&
3740 layer->isSecure()) {
3741 secureLayerIsVisible = true;
3742 }
3743 }
3744
3745 if (!isLocalScreenshot && secureLayerIsVisible) {
3746 ALOGW("FB is protected: PERMISSION_DENIED");
3747 return PERMISSION_DENIED;
3748 }
3749
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003750 // create a surface (because we're a producer, and we need to
3751 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003752 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003753
3754 // Put the screenshot Surface into async mode so that
3755 // Layer::headFenceHasSignaled will always return true and we'll latch the
3756 // first buffer regardless of whether or not its acquire fence has
3757 // signaled. This is needed to avoid a race condition in the rotation
3758 // animation. See b/30209608
3759 sur->setAsyncMode(true);
3760
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003761 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003762
Michael Lentine5a16a622015-05-21 13:48:24 -07003763 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3764 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003765 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3766 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003767
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003768 int err = 0;
3769 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003770 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003771 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3772 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003773
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003774 if (err == NO_ERROR) {
3775 ANativeWindowBuffer* buffer;
3776 /* TODO: Once we have the sync framework everywhere this can use
3777 * server-side waits on the fence that dequeueBuffer returns.
3778 */
3779 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3780 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003781 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003782 // create an EGLImage from the buffer so we can later
3783 // turn it into a texture
3784 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3785 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3786 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003787 // this binds the given EGLImage as a framebuffer for the
3788 // duration of this scope.
3789 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3790 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003791 // this will in fact render into our dequeued buffer
3792 // via an FBO, which means we didn't have to create
3793 // an EGLSurface and therefore we're not
3794 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003795 renderScreenImplLocked(
3796 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3797 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003798
Riley Andrews86639902014-08-15 12:27:24 -07003799 // Attempt to create a sync khr object that can produce a sync point. If that
3800 // isn't available, create a non-dupable sync object in the fallback path and
3801 // wait on it directly.
3802 EGLSyncKHR sync;
3803 if (!DEBUG_SCREENSHOTS) {
3804 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003805 // native fence fd will not be populated until flush() is done.
3806 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003807 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003808 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003809 }
Riley Andrews86639902014-08-15 12:27:24 -07003810 if (sync != EGL_NO_SYNC_KHR) {
3811 // get the sync fd
3812 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3813 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3814 ALOGW("captureScreen: failed to dup sync khr object");
3815 syncFd = -1;
3816 }
3817 eglDestroySyncKHR(mEGLDisplay, sync);
3818 } else {
3819 // fallback path
3820 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3821 if (sync != EGL_NO_SYNC_KHR) {
3822 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3823 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3824 EGLint eglErr = eglGetError();
3825 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3826 ALOGW("captureScreen: fence wait timed out");
3827 } else {
3828 ALOGW_IF(eglErr != EGL_SUCCESS,
3829 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3830 }
3831 eglDestroySyncKHR(mEGLDisplay, sync);
3832 } else {
3833 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3834 }
3835 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003836 if (DEBUG_SCREENSHOTS) {
3837 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3838 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3839 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3840 hw, minLayerZ, maxLayerZ);
3841 delete [] pixels;
3842 }
3843
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003844 } else {
3845 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3846 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003847 window->cancelBuffer(window, buffer, syncFd);
3848 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003849 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003850 // destroy our image
3851 eglDestroyImageKHR(mEGLDisplay, image);
3852 } else {
3853 result = BAD_VALUE;
3854 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003855 if (buffer) {
3856 // queueBuffer takes ownership of syncFd
3857 result = window->queueBuffer(window, buffer, syncFd);
3858 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003859 }
3860 } else {
3861 result = BAD_VALUE;
3862 }
3863 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3864 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003865
Mathias Agopian74c40c02010-09-29 13:02:36 -07003866 return result;
3867}
3868
Mathias Agopiand5556842013-09-19 17:08:37 -07003869void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3870 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003871 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003872 for (size_t y=0 ; y<h ; y++) {
3873 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3874 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003875 if (p[x] != 0xFF000000) return;
3876 }
3877 }
3878 ALOGE("*** we just took a black screenshot ***\n"
3879 "requested minz=%d, maxz=%d, layerStack=%d",
3880 minLayerZ, maxLayerZ, hw->getLayerStack());
3881 const LayerVector& layers( mDrawingState.layersSortedByZ );
3882 const size_t count = layers.size();
3883 for (size_t i=0 ; i<count ; ++i) {
3884 const sp<Layer>& layer(layers[i]);
3885 const Layer::State& state(layer->getDrawingState());
3886 const bool visible = (state.layerStack == hw->getLayerStack())
3887 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3888 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003889 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003890 visible ? '+' : '-',
3891 i, layer->getName().string(), state.layerStack, state.z,
3892 layer->isVisible(), state.flags, state.alpha);
3893 }
3894 }
3895}
3896
Pablo Ceballosce796e72016-02-04 19:10:51 -08003897bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3898 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3899 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3900}
3901
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003902// ---------------------------------------------------------------------------
3903
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003904SurfaceFlinger::LayerVector::LayerVector() {
3905}
3906
3907SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003908 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003909}
3910
3911int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3912 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003913{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003914 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003915 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3916 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003917
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003918 uint32_t ls = l->getCurrentState().layerStack;
3919 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003920 if (ls != rs)
3921 return ls - rs;
3922
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003923 uint32_t lz = l->getCurrentState().z;
3924 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003925 if (lz != rz)
3926 return lz - rz;
3927
3928 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003929}
3930
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003931}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003932
3933
3934#if defined(__gl_h_)
3935#error "don't include gl/gl.h in this file"
3936#endif
3937
3938#if defined(__gl2_h_)
3939#error "don't include gl2/gl2.h in this file"
3940#endif