blob: 30ebfd56f60d99889e250a75a0ff4ee81cd2ba0c [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>
Keun young Park63f165f2012-08-31 10:53:36 -070024#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080025#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070026#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070027
28#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080029
30#include <cutils/log.h>
31#include <cutils/properties.h>
32
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070033#include <binder/IPCThreadState.h>
34#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070035#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Mathias Agopianc666cae2012-07-25 18:56:13 -070038#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070039#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070040
Mathias Agopian921e6ac2012-07-23 23:11:29 -070041#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070043#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070044#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080046#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070047
48#include <ui/GraphicBufferAllocator.h>
49#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070050#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080051
Mathias Agopiancde87a32012-09-13 14:09:01 -070052#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080053#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070056#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080057#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080058
Mathias Agopian921e6ac2012-07-23 23:11:29 -070059#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070060#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian3e25fd82013-04-22 17:52:16 +020062#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080063#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020064#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080065#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070066#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070067#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070068#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080069#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080070#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073
Mathias Agopiana4912602012-07-12 14:25:33 -070074#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070075#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070076#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopianff2ed702013-09-01 21:36:12 -070078#include "Effects/Daltonizer.h"
79
Mathias Agopian875d8e12013-06-07 15:35:48 -070080#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070081#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070082
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#define DISPLAY_COUNT 1
84
Mathias Agopianfee2b462013-07-03 12:34:01 -070085/*
86 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 * black pixels.
88 */
89#define DEBUG_SCREENSHOTS false
90
Mathias Agopianca088332013-03-28 17:44:13 -070091EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
92
Evgenii Stepanov22819272016-07-14 14:17:24 -070093// Workaround for b/30067360: /proc/self/environ inaccessible in SurfaceFlinger
94// => ASan fails to read ASAN_OPTIONS => alloc-dealloc-mismatch bug is not
95// suppressed and prevents the device from booting.
96#ifndef __has_feature
97#define __has_feature(x) 0
98#endif
99#if __has_feature(address_sanitizer)
100__attribute__((visibility("default")))
101extern "C" const char* __asan_default_options() {
102 return "alloc_dealloc_mismatch=0";
103}
104#endif
105
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800106namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700107
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108// This is the phase offset in nanoseconds of the software vsync event
109// relative to the vsync event reported by HWComposer. The software vsync
110// event is when SurfaceFlinger and Choreographer-based applications run each
111// frame.
112//
113// This phase offset allows adjustment of the minimum latency from application
114// wake-up (by Choregographer) time to the time at which the resulting window
115// image is displayed. This value may be either positive (after the HW vsync)
116// or negative (before the HW vsync). Setting it to 0 will result in a
117// minimum latency of two vsync periods because the app and SurfaceFlinger
118// will run just after the HW vsync. Setting it to a positive number will
119// result in the minimum latency being:
120//
121// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
122//
123// Note that reducing this latency makes it more likely for the applications
124// to not have their window content image ready in time. When this happens
125// the latency will end up being an additional vsync period, and animations
126// will hiccup. Therefore, this latency should be tuned somewhat
127// conservatively (or at least with awareness of the trade-off being made).
128static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
129
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700130// This is the phase offset at which SurfaceFlinger's composition runs.
131static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
132
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800133// ---------------------------------------------------------------------------
134
Mathias Agopian99b49842011-06-27 16:05:52 -0700135const String16 sHardwareTest("android.permission.HARDWARE_TEST");
136const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
137const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
138const String16 sDump("android.permission.DUMP");
139
140// ---------------------------------------------------------------------------
141
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800142SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700143 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800144 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700145 mTransactionPending(false),
146 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700147 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700148 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700149 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800150 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800151 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800152 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800153 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800154 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800155 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700156 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700157 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700158 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700159 mDebugInSwapBuffers(0),
160 mLastSwapBufferTime(0),
161 mDebugInTransaction(0),
162 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700163 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700164 mForceFullDamage(false),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000165 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700166 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700167 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800168 mHasColorMatrix(false),
169 mHasPoweredOff(false),
170 mFrameBuckets(),
171 mTotalTime(0),
172 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800173{
Steve Blocka19954a2012-01-04 20:05:49 +0000174 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175
176 // debugging stuff...
177 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700178
Mathias Agopianb4b17302013-03-20 18:36:41 -0700179 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700180 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700181
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800182 property_get("debug.sf.showupdates", value, "0");
183 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700184
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700185 property_get("debug.sf.ddms", value, "0");
186 mDebugDDMS = atoi(value);
187 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700188 if (!startDdmConnection()) {
189 // start failed, and DDMS debugging not enabled
190 mDebugDDMS = 0;
191 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700192 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700193 ALOGI_IF(mDebugRegion, "showupdates enabled");
194 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700195
196 property_get("debug.sf.disable_backpressure", value, "0");
197 mPropagateBackpressure = !atoi(value);
198 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza3cf4bfe2016-08-02 10:27:31 -0700199
200 property_get("debug.sf.disable_hwc_vds", value, "0");
201 mUseHwcVirtualDisplays = !atoi(value);
202 ALOGI_IF(!mUseHwcVirtualDisplays, "Disabling HWC virtual displays");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203}
204
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800205void SurfaceFlinger::onFirstRef()
206{
207 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800208}
209
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800210SurfaceFlinger::~SurfaceFlinger()
211{
Mathias Agopiana4912602012-07-12 14:25:33 -0700212 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
213 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
214 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800215}
216
Dan Stozac7014012014-02-14 15:03:43 -0800217void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800218{
219 // the window manager died on us. prepare its eulogy.
220
Andy McFadden13a082e2012-08-24 10:16:42 -0700221 // restore initial conditions (default device unblank, etc)
222 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800223
224 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700225 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800226}
227
Mathias Agopian7e27f052010-05-28 14:22:23 -0700228sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800229{
Mathias Agopian96f08192010-06-02 23:28:45 -0700230 sp<ISurfaceComposerClient> bclient;
231 sp<Client> client(new Client(this));
232 status_t err = client->initCheck();
233 if (err == NO_ERROR) {
234 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800235 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800236 return bclient;
237}
238
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700239sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
240 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700241{
242 class DisplayToken : public BBinder {
243 sp<SurfaceFlinger> flinger;
244 virtual ~DisplayToken() {
245 // no more references, this display must be terminated
246 Mutex::Autolock _l(flinger->mStateLock);
247 flinger->mCurrentState.displays.removeItem(this);
248 flinger->setTransactionFlags(eDisplayTransactionNeeded);
249 }
250 public:
251 DisplayToken(const sp<SurfaceFlinger>& flinger)
252 : flinger(flinger) {
253 }
254 };
255
256 sp<BBinder> token = new DisplayToken(this);
257
258 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700259 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700260 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700261 mCurrentState.displays.add(token, info);
262
263 return token;
264}
265
Jesse Hall6c913be2013-08-08 12:15:49 -0700266void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
267 Mutex::Autolock _l(mStateLock);
268
269 ssize_t idx = mCurrentState.displays.indexOfKey(display);
270 if (idx < 0) {
271 ALOGW("destroyDisplay: invalid display token");
272 return;
273 }
274
275 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
276 if (!info.isVirtualDisplay()) {
277 ALOGE("destroyDisplay called for non-virtual display");
278 return;
279 }
280
281 mCurrentState.displays.removeItemsAt(idx);
282 setTransactionFlags(eDisplayTransactionNeeded);
283}
284
Jesse Hall692c7232012-11-08 15:41:56 -0800285void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800286 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800287 ALOGW_IF(mBuiltinDisplays[type],
288 "Overwriting display token for display type %d", type);
289 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800290 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700291 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800292 mCurrentState.displays.add(mBuiltinDisplays[type], info);
293}
294
Mathias Agopiane57f2922012-08-09 16:29:12 -0700295sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700296 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700297 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
298 return NULL;
299 }
Jesse Hall692c7232012-11-08 15:41:56 -0800300 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700301}
302
Jamie Gennis9a78c902011-01-12 18:30:40 -0800303sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
304{
305 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
306 return gba;
307}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700308
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800309void SurfaceFlinger::bootFinished()
310{
311 const nsecs_t now = systemTime();
312 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000313 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700314 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700315
316 // wait patiently for the window manager death
317 const String16 name("window");
318 sp<IBinder> window(defaultServiceManager()->getService(name));
319 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700320 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700321 }
322
323 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700324 // formerly we would just kill the process, but we now ask it to exit so it
325 // can choose where to stop the animation.
326 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700327
328 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
329 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
330 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331}
332
Mathias Agopian3f844832013-08-07 21:24:32 -0700333void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700334 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700335 RenderEngine& engine;
336 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700337 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700338 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
339 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700340 }
341 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700342 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700343 return true;
344 }
345 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700346 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700347}
348
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700349class DispSyncSource : public VSyncSource, private DispSync::Callback {
350public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700351 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000352 const char* name) :
353 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700354 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700355 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000356 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
357 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700358 mDispSync(dispSync),
359 mCallbackMutex(),
360 mCallback(),
361 mVsyncMutex(),
362 mPhaseOffset(phaseOffset),
363 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700364
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700365 virtual ~DispSyncSource() {}
366
367 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700368 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700369 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000370 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700371 static_cast<DispSync::Callback*>(this));
372 if (err != NO_ERROR) {
373 ALOGE("error registering vsync callback: %s (%d)",
374 strerror(-err), err);
375 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700376 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 } else {
378 status_t err = mDispSync->removeEventListener(
379 static_cast<DispSync::Callback*>(this));
380 if (err != NO_ERROR) {
381 ALOGE("error unregistering vsync callback: %s (%d)",
382 strerror(-err), err);
383 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700384 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700385 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700386 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700387 }
388
389 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700390 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700391 mCallback = callback;
392 }
393
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700394 virtual void setPhaseOffset(nsecs_t phaseOffset) {
395 Mutex::Autolock lock(mVsyncMutex);
396
397 // Normalize phaseOffset to [0, period)
398 auto period = mDispSync->getPeriod();
399 phaseOffset %= period;
400 if (phaseOffset < 0) {
401 // If we're here, then phaseOffset is in (-period, 0). After this
402 // operation, it will be in (0, period)
403 phaseOffset += period;
404 }
405 mPhaseOffset = phaseOffset;
406
407 // If we're not enabled, we don't need to mess with the listeners
408 if (!mEnabled) {
409 return;
410 }
411
412 // Remove the listener with the old offset
413 status_t err = mDispSync->removeEventListener(
414 static_cast<DispSync::Callback*>(this));
415 if (err != NO_ERROR) {
416 ALOGE("error unregistering vsync callback: %s (%d)",
417 strerror(-err), err);
418 }
419
420 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000421 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700422 static_cast<DispSync::Callback*>(this));
423 if (err != NO_ERROR) {
424 ALOGE("error registering vsync callback: %s (%d)",
425 strerror(-err), err);
426 }
427 }
428
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700429private:
430 virtual void onDispSyncEvent(nsecs_t when) {
431 sp<VSyncSource::Callback> callback;
432 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700433 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700434 callback = mCallback;
435
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700436 if (mTraceVsync) {
437 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700438 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700439 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700440 }
441
442 if (callback != NULL) {
443 callback->onVSyncEvent(when);
444 }
445 }
446
Tim Murray4a4e4a22016-04-19 16:29:23 +0000447 const char* const mName;
448
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700449 int mValue;
450
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700451 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700452 const String8 mVsyncOnLabel;
453 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700454
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700456
457 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700458 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700459
460 Mutex mVsyncMutex; // Protects the following
461 nsecs_t mPhaseOffset;
462 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700463};
464
465void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700466 ALOGI( "SurfaceFlinger's main thread ready to run. "
467 "Initializing graphics H/W...");
468
Dan Stoza9e56aa02015-11-02 13:00:03 -0800469 { // Autolock scope
470 Mutex::Autolock _l(mStateLock);
471
472 // initialize EGL for the default display
473 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
474 eglInitialize(mEGLDisplay, NULL, NULL);
475
476 // start the EventThread
477 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
478 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000479 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800480 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
481 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000482 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800483 mEventQueue.setEventThread(mSFEventThread);
484
Tim Murrayacff43d2016-07-29 13:57:24 -0700485 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700486 struct sched_param param = {0};
Tim Murray35520632016-09-07 12:18:17 -0700487 param.sched_priority = 2;
Tim Murray41a38532016-06-22 12:42:10 -0700488 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
489 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
490 }
491
Dan Stoza9e56aa02015-11-02 13:00:03 -0800492 // Get a RenderEngine for the given display / config (can't fail)
493 mRenderEngine = RenderEngine::create(mEGLDisplay,
494 HAL_PIXEL_FORMAT_RGBA_8888);
495 }
496
497 // Drop the state lock while we initialize the hardware composer. We drop
498 // the lock because on creation, it will call back into SurfaceFlinger to
499 // initialize the primary display.
500 mHwc = new HWComposer(this);
501 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
502
Jesse Hall692c7232012-11-08 15:41:56 -0800503 Mutex::Autolock _l(mStateLock);
504
Mathias Agopian875d8e12013-06-07 15:35:48 -0700505 // retrieve the EGL context that was selected/created
506 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700507
Mathias Agopianda27af92012-09-13 18:17:13 -0700508 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
509 "couldn't create EGLContext");
510
Dan Stoza9e56aa02015-11-02 13:00:03 -0800511 // make the GLContext current so that we can create textures when creating
512 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700513 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
514
Jamie Gennisd1700752013-10-14 12:22:52 -0700515 mEventControlThread = new EventControlThread(this);
516 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
517
Mathias Agopian92a979a2012-08-02 18:32:23 -0700518 // initialize our drawing state
519 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700520
Andy McFadden13a082e2012-08-24 10:16:42 -0700521 // set initial conditions (e.g. unblank default device)
522 initializeDisplays();
523
Dan Stoza4e637772016-07-28 13:31:51 -0700524 mRenderEngine->primeCache();
525
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700526 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700527 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528
Dan Stoza9e56aa02015-11-02 13:00:03 -0800529 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700530}
531
Mathias Agopiana67e4182012-06-19 17:26:12 -0700532void SurfaceFlinger::startBootAnim() {
533 // start boot animation
534 property_set("service.bootanim.exit", "0");
535 property_set("ctl.start", "bootanim");
536}
537
Mathias Agopian875d8e12013-06-07 15:35:48 -0700538size_t SurfaceFlinger::getMaxTextureSize() const {
539 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700540}
541
Mathias Agopian875d8e12013-06-07 15:35:48 -0700542size_t SurfaceFlinger::getMaxViewportDims() const {
543 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700544}
545
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800547
Jamie Gennis582270d2011-08-17 18:19:00 -0700548bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800549 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800550 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800551 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700552 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800553}
554
Dan Stoza7f7da322014-05-02 15:26:25 -0700555status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
556 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700557 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700558 return BAD_VALUE;
559 }
560
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500561 if (!display.get())
562 return NAME_NOT_FOUND;
563
Jesse Hall692c7232012-11-08 15:41:56 -0800564 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700565 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800566 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700567 type = i;
568 break;
569 }
570 }
571
572 if (type < 0) {
573 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700574 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700575
Mathias Agopian8b736f12012-08-13 17:54:26 -0700576 // TODO: Not sure if display density should handled by SF any longer
577 class Density {
578 static int getDensityFromProperty(char const* propName) {
579 char property[PROPERTY_VALUE_MAX];
580 int density = 0;
581 if (property_get(propName, property, NULL) > 0) {
582 density = atoi(property);
583 }
584 return density;
585 }
586 public:
587 static int getEmuDensity() {
588 return getDensityFromProperty("qemu.sf.lcd_density"); }
589 static int getBuildDensity() {
590 return getDensityFromProperty("ro.sf.lcd_density"); }
591 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700592
Dan Stoza7f7da322014-05-02 15:26:25 -0700593 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700594
Dan Stoza9e56aa02015-11-02 13:00:03 -0800595 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700596 DisplayInfo info = DisplayInfo();
597
Dan Stoza9e56aa02015-11-02 13:00:03 -0800598 float xdpi = hwConfig->getDpiX();
599 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700600
601 if (type == DisplayDevice::DISPLAY_PRIMARY) {
602 // The density of the device is provided by a build property
603 float density = Density::getBuildDensity() / 160.0f;
604 if (density == 0) {
605 // the build doesn't provide a density -- this is wrong!
606 // use xdpi instead
607 ALOGE("ro.sf.lcd_density must be defined as a build property");
608 density = xdpi / 160.0f;
609 }
610 if (Density::getEmuDensity()) {
611 // if "qemu.sf.lcd_density" is specified, it overrides everything
612 xdpi = ydpi = density = Density::getEmuDensity();
613 density /= 160.0f;
614 }
615 info.density = density;
616
617 // TODO: this needs to go away (currently needed only by webkit)
618 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
619 info.orientation = hw->getOrientation();
620 } else {
621 // TODO: where should this value come from?
622 static const int TV_DENSITY = 213;
623 info.density = TV_DENSITY / 160.0f;
624 info.orientation = 0;
625 }
626
Dan Stoza9e56aa02015-11-02 13:00:03 -0800627 info.w = hwConfig->getWidth();
628 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700629 info.xdpi = xdpi;
630 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800631 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700632 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800633
Andy McFadden91b2ca82014-06-13 14:04:23 -0700634 // This is how far in advance a buffer must be queued for
635 // presentation at a given time. If you want a buffer to appear
636 // on the screen at time N, you must submit the buffer before
637 // (N - presentationDeadline).
638 //
639 // Normally it's one full refresh period (to give SF a chance to
640 // latch the buffer), but this can be reduced by configuring a
641 // DispSync offset. Any additional delays introduced by the hardware
642 // composer or panel must be accounted for here.
643 //
644 // We add an additional 1ms to allow for processing time and
645 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800646 info.presentationDeadline = hwConfig->getVsyncPeriod() -
647 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700648
649 // All non-virtual displays are currently considered secure.
650 info.secure = true;
651
Michael Wright28f24d02016-07-12 13:30:53 -0700652 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700653 }
654
Dan Stoza7f7da322014-05-02 15:26:25 -0700655 return NO_ERROR;
656}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700657
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800658status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700659 DisplayStatInfo* stats) {
660 if (stats == NULL) {
661 return BAD_VALUE;
662 }
663
664 // FIXME for now we always return stats for the primary display
665 memset(stats, 0, sizeof(*stats));
666 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
667 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
668 return NO_ERROR;
669}
670
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700671int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700672 sp<DisplayDevice> device(getDisplayDevice(display));
673 if (device != NULL) {
674 return device->getActiveConfig();
675 }
676 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700677}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700678
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700679void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
680 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
681 this);
682 int32_t type = hw->getDisplayType();
683 int currentMode = hw->getActiveConfig();
684
685 if (mode == currentMode) {
686 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
687 return;
688 }
689
690 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
691 ALOGW("Trying to set config for virtual display");
692 return;
693 }
694
695 hw->setActiveConfig(mode);
696 getHwComposer().setActiveConfig(type, mode);
697}
698
699status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
700 class MessageSetActiveConfig: public MessageBase {
701 SurfaceFlinger& mFlinger;
702 sp<IBinder> mDisplay;
703 int mMode;
704 public:
705 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
706 int mode) :
707 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
708 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700709 Vector<DisplayInfo> configs;
710 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700711 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700712 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700713 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700714 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700715 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700716 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
717 if (hw == NULL) {
718 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700719 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700720 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
721 ALOGW("Attempt to set active config = %d for virtual display",
722 mMode);
723 } else {
724 mFlinger.setActiveConfigInternal(hw, mMode);
725 }
726 return true;
727 }
728 };
729 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
730 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700731 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700732}
Michael Wright28f24d02016-07-12 13:30:53 -0700733status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
734 Vector<android_color_mode_t>* outColorModes) {
735 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
736 return BAD_VALUE;
737 }
738
739 if (!display.get()) {
740 return NAME_NOT_FOUND;
741 }
742
743 int32_t type = NAME_NOT_FOUND;
744 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
745 if (display == mBuiltinDisplays[i]) {
746 type = i;
747 break;
748 }
749 }
750
751 if (type < 0) {
752 return type;
753 }
754
755 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
756 outColorModes->clear();
757 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
758
759 return NO_ERROR;
760}
761
762android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
763 sp<DisplayDevice> device(getDisplayDevice(display));
764 if (device != nullptr) {
765 return device->getActiveColorMode();
766 }
767 return static_cast<android_color_mode_t>(BAD_VALUE);
768}
769
770void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
771 android_color_mode_t mode) {
772 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
773 this);
774 int32_t type = hw->getDisplayType();
775 android_color_mode_t currentMode = hw->getActiveColorMode();
776
777 if (mode == currentMode) {
778 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
779 return;
780 }
781
782 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
783 ALOGW("Trying to set config for virtual display");
784 return;
785 }
786
787 hw->setActiveColorMode(mode);
788 getHwComposer().setActiveColorMode(type, mode);
789}
790
791
792status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
793 android_color_mode_t colorMode) {
794 class MessageSetActiveColorMode: public MessageBase {
795 SurfaceFlinger& mFlinger;
796 sp<IBinder> mDisplay;
797 android_color_mode_t mMode;
798 public:
799 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
800 android_color_mode_t mode) :
801 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
802 virtual bool handler() {
803 Vector<android_color_mode_t> modes;
804 mFlinger.getDisplayColorModes(mDisplay, &modes);
805 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
806 if (mMode < 0 || !exists) {
807 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
808 mDisplay.get());
809 return true;
810 }
811 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
812 if (hw == nullptr) {
813 ALOGE("Attempt to set active color mode = %d for null display %p",
814 mMode, mDisplay.get());
815 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
816 ALOGW("Attempt to set active color mode= %d for virtual display",
817 mMode);
818 } else {
819 mFlinger.setActiveColorModeInternal(hw, mMode);
820 }
821 return true;
822 }
823 };
824 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
825 postMessageSync(msg);
826 return NO_ERROR;
827}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700828
Svetoslavd85084b2014-03-20 10:28:31 -0700829status_t SurfaceFlinger::clearAnimationFrameStats() {
830 Mutex::Autolock _l(mStateLock);
831 mAnimFrameTracker.clearStats();
832 return NO_ERROR;
833}
834
835status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
836 Mutex::Autolock _l(mStateLock);
837 mAnimFrameTracker.getStats(outStats);
838 return NO_ERROR;
839}
840
Dan Stozac4f471e2016-03-24 09:31:08 -0700841status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
842 HdrCapabilities* outCapabilities) const {
843 Mutex::Autolock _l(mStateLock);
844
845 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
846 if (displayDevice == nullptr) {
847 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
848 return BAD_VALUE;
849 }
850
851 std::unique_ptr<HdrCapabilities> capabilities =
852 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
853 if (capabilities) {
854 std::swap(*outCapabilities, *capabilities);
855 } else {
856 return BAD_VALUE;
857 }
858
859 return NO_ERROR;
860}
861
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800862// ----------------------------------------------------------------------------
863
864sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800865 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700866}
867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800868// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800869
870void SurfaceFlinger::waitForEvent() {
871 mEventQueue.waitMessage();
872}
873
874void SurfaceFlinger::signalTransaction() {
875 mEventQueue.invalidate();
876}
877
878void SurfaceFlinger::signalLayerUpdate() {
879 mEventQueue.invalidate();
880}
881
882void SurfaceFlinger::signalRefresh() {
883 mEventQueue.refresh();
884}
885
886status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800887 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800888 return mEventQueue.postMessage(msg, reltime);
889}
890
891status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800892 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800893 status_t res = mEventQueue.postMessage(msg, reltime);
894 if (res == NO_ERROR) {
895 msg->wait();
896 }
897 return res;
898}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800899
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700900void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700901 do {
902 waitForEvent();
903 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800904}
905
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700906void SurfaceFlinger::enableHardwareVsync() {
907 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700908 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700909 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700910 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
911 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700912 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700913 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700914}
915
Jesse Hall948fe0c2013-10-14 12:56:09 -0700916void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700917 Mutex::Autolock _l(mHWVsyncLock);
918
Jesse Hall948fe0c2013-10-14 12:56:09 -0700919 if (makeAvailable) {
920 mHWVsyncAvailable = true;
921 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700922 // Hardware vsync is not currently available, so abort the resync
923 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700924 return;
925 }
926
Dan Stoza9e56aa02015-11-02 13:00:03 -0800927 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
928 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700929
930 mPrimaryDispSync.reset();
931 mPrimaryDispSync.setPeriod(period);
932
933 if (!mPrimaryHWVsyncEnabled) {
934 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700935 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
936 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700937 mPrimaryHWVsyncEnabled = true;
938 }
939}
940
Jesse Hall948fe0c2013-10-14 12:56:09 -0700941void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700942 Mutex::Autolock _l(mHWVsyncLock);
943 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700944 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
945 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700946 mPrimaryDispSync.endResync();
947 mPrimaryHWVsyncEnabled = false;
948 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700949 if (makeUnavailable) {
950 mHWVsyncAvailable = false;
951 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700952}
953
Tim Murray4a4e4a22016-04-19 16:29:23 +0000954void SurfaceFlinger::resyncWithRateLimit() {
955 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
956 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700957 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000958 }
959}
960
Dan Stoza9e56aa02015-11-02 13:00:03 -0800961void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700962 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700963
Jamie Gennisd1700752013-10-14 12:22:52 -0700964 { // Scope for the lock
965 Mutex::Autolock _l(mHWVsyncLock);
966 if (type == 0 && mPrimaryHWVsyncEnabled) {
967 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700968 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700969 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700970
971 if (needsHwVsync) {
972 enableHardwareVsync();
973 } else {
974 disableHardwareVsync(false);
975 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700976}
977
Dan Stoza9e56aa02015-11-02 13:00:03 -0800978void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
979 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
980 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
981 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700982
Dan Stoza9e56aa02015-11-02 13:00:03 -0800983 // All non-virtual displays are currently considered secure.
984 bool isSecure = true;
985
986 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
987 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
988 wp<IBinder> token = mBuiltinDisplays[type];
989
990 sp<IGraphicBufferProducer> producer;
991 sp<IGraphicBufferConsumer> consumer;
992 BufferQueue::createBufferQueue(&producer, &consumer,
993 new GraphicBufferAlloc());
994
995 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
996 DisplayDevice::DISPLAY_PRIMARY, consumer);
997 sp<DisplayDevice> hw = new DisplayDevice(this,
998 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
999 producer, mRenderEngine->getEGLConfig());
1000 mDisplays.add(token, hw);
1001 } else {
1002 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001003 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001004 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001005 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001006 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001007 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1008 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001009 }
1010 setTransactionFlags(eDisplayTransactionNeeded);
1011
Andy McFadden9e9689c2012-10-10 18:17:51 -07001012 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001013 }
Mathias Agopian86303202012-07-24 22:46:10 -07001014}
1015
Dan Stoza9e56aa02015-11-02 13:00:03 -08001016void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001017 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001018 getHwComposer().setVsyncEnabled(disp,
1019 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001020}
1021
Mathias Agopian4fec8732012-06-29 14:12:52 -07001022void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001023 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001024 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001025 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001026 bool frameMissed = !mHadClientComposition &&
1027 mPreviousPresentFence != Fence::NO_FENCE &&
1028 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1029 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001030 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001031 signalLayerUpdate();
1032 break;
1033 }
1034
Dan Stoza6b9454d2014-11-07 16:00:59 -08001035 bool refreshNeeded = handleMessageTransaction();
1036 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001037 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001038 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001039 // Signal a refresh if a transaction modified the window state,
1040 // a new buffer was latched, or if HWC has requested a full
1041 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001042 signalRefresh();
1043 }
1044 break;
1045 }
1046 case MessageQueue::REFRESH: {
1047 handleMessageRefresh();
1048 break;
1049 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001050 }
1051}
1052
Dan Stoza6b9454d2014-11-07 16:00:59 -08001053bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001054 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001055 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001056 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001057 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001058 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001059 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001060}
1061
Dan Stoza6b9454d2014-11-07 16:00:59 -08001062bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001063 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001064 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001065}
1066
1067void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001068 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001069
Pablo Ceballos40845df2016-01-25 17:41:15 -08001070 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001071
Dan Stoza05dacfb2016-07-01 13:33:38 -07001072 preComposition();
1073 rebuildLayerStacks();
1074 setUpHWComposer();
1075 doDebugFlashRegions();
1076 doComposition();
1077 postComposition(refreshStartTime);
1078
1079 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001080
1081 mHadClientComposition = false;
1082 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1083 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1084 mHadClientComposition = mHadClientComposition ||
1085 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1086 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001087
Dan Stoza9e56aa02015-11-02 13:00:03 -08001088 // Release any buffers which were replaced this frame
1089 for (auto& layer : mLayersWithQueuedFrames) {
1090 layer->releasePendingBuffer();
1091 }
1092 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001093}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001094
Mathias Agopiancd60f992012-08-16 16:28:27 -07001095void SurfaceFlinger::doDebugFlashRegions()
1096{
1097 // is debugging enabled
1098 if (CC_LIKELY(!mDebugRegion))
1099 return;
1100
1101 const bool repaintEverything = mRepaintEverything;
1102 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1103 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001104 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001105 // transform the dirty region into this screen's coordinate space
1106 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1107 if (!dirtyRegion.isEmpty()) {
1108 // redraw the whole screen
1109 doComposeSurfaces(hw, Region(hw->bounds()));
1110
1111 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001112 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001113 RenderEngine& engine(getRenderEngine());
1114 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1115
Mathias Agopianda27af92012-09-13 18:17:13 -07001116 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001117 }
1118 }
1119 }
1120
1121 postFramebuffer();
1122
1123 if (mDebugRegion > 1) {
1124 usleep(mDebugRegion * 1000);
1125 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001126
Dan Stoza9e56aa02015-11-02 13:00:03 -08001127 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001128 auto& displayDevice = mDisplays[displayId];
1129 if (!displayDevice->isDisplayOn()) {
1130 continue;
1131 }
1132
1133 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001134 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1135 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001136 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001137}
1138
1139void SurfaceFlinger::preComposition()
1140{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001141 ATRACE_CALL();
1142 ALOGV("preComposition");
1143
Mathias Agopiancd60f992012-08-16 16:28:27 -07001144 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001145 const LayerVector& layers(mDrawingState.layersSortedByZ);
1146 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001147 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001148 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001149 needExtraInvalidate = true;
1150 }
1151 }
1152 if (needExtraInvalidate) {
1153 signalLayerUpdate();
1154 }
1155}
1156
Pablo Ceballos40845df2016-01-25 17:41:15 -08001157void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001158{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001159 ATRACE_CALL();
1160 ALOGV("postComposition");
1161
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001162 const LayerVector& layers(mDrawingState.layersSortedByZ);
1163 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001164 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001165 bool frameLatched = layers[i]->onPostComposition();
1166 if (frameLatched) {
1167 recordBufferingStats(layers[i]->getName().string(),
1168 layers[i]->getOccupancyHistory(false));
1169 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001170 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001171
Dan Stoza9e56aa02015-11-02 13:00:03 -08001172 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001173
1174 if (presentFence->isValid()) {
1175 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1176 enableHardwareVsync();
1177 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001178 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001179 }
1180 }
1181
Dan Stozab90cf072015-03-05 11:05:59 -08001182 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001183 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001184 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001185 enableHardwareVsync();
1186 }
1187 }
1188
Pablo Ceballos40845df2016-01-25 17:41:15 -08001189 mFenceTracker.addFrame(refreshStartTime, presentFence,
1190 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1191
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001192 if (mAnimCompositionPending) {
1193 mAnimCompositionPending = false;
1194
Jesse Halla9a1b002013-02-27 16:39:25 -08001195 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001196 mAnimFrameTracker.setActualPresentFence(presentFence);
1197 } else {
1198 // The HWC doesn't support present fences, so use the refresh
1199 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001200 nsecs_t presentTime =
1201 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001202 mAnimFrameTracker.setActualPresentTime(presentTime);
1203 }
1204 mAnimFrameTracker.advanceFrame();
1205 }
Dan Stozab90cf072015-03-05 11:05:59 -08001206
1207 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1208 return;
1209 }
1210
1211 nsecs_t currentTime = systemTime();
1212 if (mHasPoweredOff) {
1213 mHasPoweredOff = false;
1214 } else {
1215 nsecs_t period = mPrimaryDispSync.getPeriod();
1216 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1217 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1218 if (numPeriods < NUM_BUCKETS - 1) {
1219 mFrameBuckets[numPeriods] += elapsedTime;
1220 } else {
1221 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1222 }
1223 mTotalTime += elapsedTime;
1224 }
1225 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001226}
1227
1228void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001229 ATRACE_CALL();
1230 ALOGV("rebuildLayerStacks");
1231
Mathias Agopiancd60f992012-08-16 16:28:27 -07001232 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001233 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001234 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001235 mVisibleRegionsDirty = false;
1236 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001237
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001238 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001239 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001240 Region opaqueRegion;
1241 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001242 Vector<sp<Layer>> layersSortedByZ;
1243 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1244 const Transform& tr(displayDevice->getTransform());
1245 const Rect bounds(displayDevice->getBounds());
1246 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001247 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001248 displayDevice->getLayerStack(), dirtyRegion,
1249 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001250
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001251 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001252 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001253 const sp<Layer>& layer(layers[i]);
1254 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001255 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001256 Region drawRegion(tr.transform(
1257 layer->visibleNonTransparentRegion));
1258 drawRegion.andSelf(bounds);
1259 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001260 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001261 } else {
1262 // Clear out the HWC layer if this layer was
1263 // previously visible, but no longer is
1264 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1265 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001266 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001267 }
1268 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001269 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001270 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1271 displayDevice->undefinedRegion.set(bounds);
1272 displayDevice->undefinedRegion.subtractSelf(
1273 tr.transform(opaqueRegion));
1274 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001275 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001276 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001277}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001278
Mathias Agopiancd60f992012-08-16 16:28:27 -07001279void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001280 ATRACE_CALL();
1281 ALOGV("setUpHWComposer");
1282
Jesse Hall028dc8f2013-08-20 16:35:32 -07001283 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001284 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1285 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1286 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1287
1288 // If nothing has changed (!dirty), don't recompose.
1289 // If something changed, but we don't currently have any visible layers,
1290 // and didn't when we last did a composition, then skip it this time.
1291 // The second rule does two things:
1292 // - When all layers are removed from a display, we'll emit one black
1293 // frame, then nothing more until we get new layers.
1294 // - When a display is created with a private layer stack, we won't
1295 // emit any black frames until a layer is added to the layer stack.
1296 bool mustRecompose = dirty && !(empty && wasEmpty);
1297
1298 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1299 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1300 mustRecompose ? "doing" : "skipping",
1301 dirty ? "+" : "-",
1302 empty ? "+" : "-",
1303 wasEmpty ? "+" : "-");
1304
Dan Stoza71433162014-02-04 16:22:36 -08001305 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001306
1307 if (mustRecompose) {
1308 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1309 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001310 }
1311
Dan Stoza9e56aa02015-11-02 13:00:03 -08001312 // build the h/w work list
1313 if (CC_UNLIKELY(mGeometryInvalid)) {
1314 mGeometryInvalid = false;
1315 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1316 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1317 const auto hwcId = displayDevice->getHwcDisplayId();
1318 if (hwcId >= 0) {
1319 const Vector<sp<Layer>>& currentLayers(
1320 displayDevice->getVisibleLayersSortedByZ());
1321 bool foundLayerWithoutHwc = false;
1322 for (auto& layer : currentLayers) {
1323 if (!layer->hasHwcLayer(hwcId)) {
1324 auto hwcLayer = mHwc->createLayer(hwcId);
1325 if (hwcLayer) {
1326 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1327 } else {
1328 layer->forceClientComposition(hwcId);
1329 foundLayerWithoutHwc = true;
1330 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001331 }
1332 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001333
Dan Stoza9e56aa02015-11-02 13:00:03 -08001334 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001335 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001336 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001337 }
1338 }
1339 }
1340 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001341 }
Riley Andrews03414a12014-07-01 14:22:59 -07001342
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001343
1344 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1345
Dan Stoza9e56aa02015-11-02 13:00:03 -08001346 // Set the per-frame data
1347 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1348 auto& displayDevice = mDisplays[displayId];
1349 const auto hwcId = displayDevice->getHwcDisplayId();
1350 if (hwcId < 0) {
1351 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001352 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001353 if (colorMatrix != mPreviousColorMatrix) {
1354 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1355 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1356 "display %zd: %d", displayId, result);
1357 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001358 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1359 layer->setPerFrameData(displayDevice);
1360 }
1361 }
1362
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001363 mPreviousColorMatrix = colorMatrix;
1364
Dan Stoza9e56aa02015-11-02 13:00:03 -08001365 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001366 auto& displayDevice = mDisplays[displayId];
1367 if (!displayDevice->isDisplayOn()) {
1368 continue;
1369 }
1370
1371 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001372 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1373 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001374 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001375}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001376
Mathias Agopiancd60f992012-08-16 16:28:27 -07001377void SurfaceFlinger::doComposition() {
1378 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001379 ALOGV("doComposition");
1380
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001381 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001382 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001383 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001384 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001385 // transform the dirty region into this screen's coordinate space
1386 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001387
1388 // repaint the framebuffer (if needed)
1389 doDisplayComposition(hw, dirtyRegion);
1390
Mathias Agopiancd60f992012-08-16 16:28:27 -07001391 hw->dirtyRegion.clear();
1392 hw->flip(hw->swapRegion);
1393 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001394 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001395 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001396 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001397}
1398
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001399void SurfaceFlinger::postFramebuffer()
1400{
Mathias Agopian841cde52012-03-01 15:44:37 -08001401 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001402 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001403
Mathias Agopiana44b0412011-10-16 18:46:35 -07001404 const nsecs_t now = systemTime();
1405 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001406
Dan Stoza9e56aa02015-11-02 13:00:03 -08001407 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1408 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001409 if (!displayDevice->isDisplayOn()) {
1410 continue;
1411 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001412 const auto hwcId = displayDevice->getHwcDisplayId();
1413 if (hwcId >= 0) {
1414 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001415 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001416 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001417 if (displayId == 0) {
1418 // Make the default display current because the VirtualDisplayDevice
1419 // code cannot deal with dequeueBuffer() being called outside of the
1420 // composition loop; however the code below can call glFlush() which
1421 // is allowed to (and does in some case) call dequeueBuffer().
1422 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1423 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001424 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1425 sp<Fence> releaseFence = Fence::NO_FENCE;
1426 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1427 releaseFence = displayDevice->getClientTargetAcquireFence();
1428 } else {
1429 auto hwcLayer = layer->getHwcLayer(hwcId);
1430 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001431 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001432 layer->onLayerDisplayed(releaseFence);
1433 }
1434 if (hwcId >= 0) {
1435 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001436 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001437 }
1438
Mathias Agopiana44b0412011-10-16 18:46:35 -07001439 mLastSwapBufferTime = systemTime() - now;
1440 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001441
1442 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1443 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1444 logFrameStats();
1445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001446}
1447
Mathias Agopian87baae12012-07-31 12:38:26 -07001448void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001449{
Mathias Agopian841cde52012-03-01 15:44:37 -08001450 ATRACE_CALL();
1451
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001452 // here we keep a copy of the drawing state (that is the state that's
1453 // going to be overwritten by handleTransactionLocked()) outside of
1454 // mStateLock so that the side-effects of the State assignment
1455 // don't happen with mStateLock held (which can cause deadlocks).
1456 State drawingState(mDrawingState);
1457
Mathias Agopianca4d3602011-05-19 15:38:14 -07001458 Mutex::Autolock _l(mStateLock);
1459 const nsecs_t now = systemTime();
1460 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001461
Mathias Agopianca4d3602011-05-19 15:38:14 -07001462 // Here we're guaranteed that some transaction flags are set
1463 // so we can call handleTransactionLocked() unconditionally.
1464 // We call getTransactionFlags(), which will also clear the flags,
1465 // with mStateLock held to guarantee that mCurrentState won't change
1466 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001467
Mathias Agopiane57f2922012-08-09 16:29:12 -07001468 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001469 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001470
Mathias Agopianca4d3602011-05-19 15:38:14 -07001471 mLastTransactionTime = systemTime() - now;
1472 mDebugInTransaction = 0;
1473 invalidateHwcGeometry();
1474 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001475}
1476
Mathias Agopian87baae12012-07-31 12:38:26 -07001477void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001478{
1479 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001480 const size_t count = currentLayers.size();
1481
Dan Stoza7dde5992015-05-22 09:51:44 -07001482 // Notify all layers of available frames
1483 for (size_t i = 0; i < count; ++i) {
1484 currentLayers[i]->notifyAvailableFrames();
1485 }
1486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001487 /*
1488 * Traversal of the children
1489 * (perform the transaction for each of them if needed)
1490 */
1491
Mathias Agopian3559b072012-08-15 13:46:03 -07001492 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001493 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001494 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001495 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1496 if (!trFlags) continue;
1497
1498 const uint32_t flags = layer->doTransaction(0);
1499 if (flags & Layer::eVisibleRegion)
1500 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001501 }
1502 }
1503
1504 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001505 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001506 */
1507
Mathias Agopiane57f2922012-08-09 16:29:12 -07001508 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001509 // here we take advantage of Vector's copy-on-write semantics to
1510 // improve performance by skipping the transaction entirely when
1511 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001512 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1513 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001514 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001515 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001516 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001517 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001518
1519 // find the displays that were removed
1520 // (ie: in drawing state but not in current state)
1521 // also handle displays that changed
1522 // (ie: displays that are in both lists)
1523 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001524 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1525 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001526 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001527 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001528 // Call makeCurrent() on the primary display so we can
1529 // be sure that nothing associated with this display
1530 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001531 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001532 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001533 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1534 if (hw != NULL)
1535 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001536 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001537 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001538 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001539 } else {
1540 ALOGW("trying to remove the main display");
1541 }
1542 } else {
1543 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001544 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001545 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001546 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1547 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001548 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001549 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001550 // recreating the DisplayDevice, so we just remove it
1551 // from the drawing state, so that it get re-added
1552 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001553 sp<DisplayDevice> hw(getDisplayDevice(display));
1554 if (hw != NULL)
1555 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001556 mDisplays.removeItem(display);
1557 mDrawingState.displays.removeItemsAt(i);
1558 dc--; i--;
1559 // at this point we must loop to the next item
1560 continue;
1561 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001562
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001563 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001564 if (disp != NULL) {
1565 if (state.layerStack != draw[i].layerStack) {
1566 disp->setLayerStack(state.layerStack);
1567 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001568 if ((state.orientation != draw[i].orientation)
1569 || (state.viewport != draw[i].viewport)
1570 || (state.frame != draw[i].frame))
1571 {
1572 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001573 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001574 }
Michael Lentine47e45402014-07-18 15:34:25 -07001575 if (state.width != draw[i].width || state.height != draw[i].height) {
1576 disp->setDisplaySize(state.width, state.height);
1577 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001578 }
1579 }
1580 }
1581
1582 // find displays that were added
1583 // (ie: in current state but not in drawing state)
1584 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001585 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001586 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001587
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001588 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001589 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001590 sp<IGraphicBufferProducer> bqProducer;
1591 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001592 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1593 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001594
Dan Stoza9e56aa02015-11-02 13:00:03 -08001595 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001596 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001597 // Virtual displays without a surface are dormant:
1598 // they have external state (layer stack, projection,
1599 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001600 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001601
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07001602 if (mUseHwcVirtualDisplays) {
1603 int width = 0;
1604 int status = state.surface->query(
1605 NATIVE_WINDOW_WIDTH, &width);
1606 ALOGE_IF(status != NO_ERROR,
1607 "Unable to query width (%d)", status);
1608 int height = 0;
1609 status = state.surface->query(
1610 NATIVE_WINDOW_HEIGHT, &height);
1611 ALOGE_IF(status != NO_ERROR,
1612 "Unable to query height (%d)", status);
1613 int intFormat = 0;
1614 status = state.surface->query(
1615 NATIVE_WINDOW_FORMAT, &intFormat);
1616 ALOGE_IF(status != NO_ERROR,
1617 "Unable to query format (%d)", status);
1618 auto format = static_cast<android_pixel_format_t>(
1619 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001620
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07001621 mHwc->allocateVirtualDisplay(width, height, &format,
1622 &hwcId);
1623 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001624
Dan Stoza5cf424b2016-05-20 14:02:39 -07001625 // TODO: Plumb requested format back up to consumer
1626
Dan Stoza9e56aa02015-11-02 13:00:03 -08001627 sp<VirtualDisplaySurface> vds =
1628 new VirtualDisplaySurface(*mHwc,
1629 hwcId, state.surface, bqProducer,
1630 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001631
1632 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001633 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001634 }
1635 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001636 ALOGE_IF(state.surface!=NULL,
1637 "adding a supported display, but rendering "
1638 "surface is provided (%p), ignoring it",
1639 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001640 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1641 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1642 dispSurface = new FramebufferSurface(*mHwc,
1643 DisplayDevice::DISPLAY_EXTERNAL,
1644 bqConsumer);
1645 producer = bqProducer;
1646 } else {
1647 ALOGE("Attempted to add non-external non-virtual"
1648 " display");
1649 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001650 }
1651
1652 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001653 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001654 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001655 state.type, hwcId, state.isSecure, display,
1656 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001657 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001658 hw->setLayerStack(state.layerStack);
1659 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001660 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001661 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001662 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001664 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001665 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001666 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001667 }
1668 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001669 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001670 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001671
Mathias Agopian84300952012-11-21 16:02:13 -08001672 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1673 // The transform hint might have changed for some layers
1674 // (either because a display has changed, or because a layer
1675 // as changed).
1676 //
1677 // Walk through all the layers in currentLayers,
1678 // and update their transform hint.
1679 //
1680 // If a layer is visible only on a single display, then that
1681 // display is used to calculate the hint, otherwise we use the
1682 // default display.
1683 //
1684 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1685 // the hint is set before we acquire a buffer from the surface texture.
1686 //
1687 // NOTE: layer transactions have taken place already, so we use their
1688 // drawing state. However, SurfaceFlinger's own transaction has not
1689 // happened yet, so we must use the current state layer list
1690 // (soon to become the drawing state list).
1691 //
1692 sp<const DisplayDevice> disp;
1693 uint32_t currentlayerStack = 0;
1694 for (size_t i=0; i<count; i++) {
1695 // NOTE: we rely on the fact that layers are sorted by
1696 // layerStack first (so we don't have to traverse the list
1697 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001698 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001699 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001700 if (i==0 || currentlayerStack != layerStack) {
1701 currentlayerStack = layerStack;
1702 // figure out if this layerstack is mirrored
1703 // (more than one display) if so, pick the default display,
1704 // if not, pick the only display it's on.
1705 disp.clear();
1706 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1707 sp<const DisplayDevice> hw(mDisplays[dpy]);
1708 if (hw->getLayerStack() == currentlayerStack) {
1709 if (disp == NULL) {
1710 disp = hw;
1711 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001712 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001713 break;
1714 }
1715 }
1716 }
1717 }
Chet Haase91d25932013-04-11 15:24:55 -07001718 if (disp == NULL) {
1719 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1720 // redraw after transform hint changes. See bug 8508397.
1721
1722 // could be null when this layer is using a layerStack
1723 // that is not visible on any display. Also can occur at
1724 // screen off/on times.
1725 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001726 }
Chet Haase91d25932013-04-11 15:24:55 -07001727 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001728 }
1729 }
1730
1731
Mathias Agopian3559b072012-08-15 13:46:03 -07001732 /*
1733 * Perform our own transaction if needed
1734 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001735
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001736 const LayerVector& layers(mDrawingState.layersSortedByZ);
1737 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001738 // layers have been added
1739 mVisibleRegionsDirty = true;
1740 }
1741
1742 // some layers might have been removed, so
1743 // we need to update the regions they're exposing.
1744 if (mLayersRemoved) {
1745 mLayersRemoved = false;
1746 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001747 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001748 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001749 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001750 if (currentLayers.indexOf(layer) < 0) {
1751 // this layer is not visible anymore
1752 // TODO: we could traverse the tree from front to back and
1753 // compute the actual visible region
1754 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001755 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001756 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001757 Region(Rect(s.active.w, s.active.h)));
1758 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001759 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001760 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001761 }
1762
1763 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001764
1765 updateCursorAsync();
1766}
1767
1768void SurfaceFlinger::updateCursorAsync()
1769{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001770 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1771 auto& displayDevice = mDisplays[displayId];
1772 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001773 continue;
1774 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001775
1776 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1777 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001778 }
1779 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001780}
1781
1782void SurfaceFlinger::commitTransaction()
1783{
1784 if (!mLayersPendingRemoval.isEmpty()) {
1785 // Notify removed layers now that they can't be drawn from
1786 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001787 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1788 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001789 mLayersPendingRemoval[i]->onRemoved();
1790 }
1791 mLayersPendingRemoval.clear();
1792 }
1793
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001794 // If this transaction is part of a window animation then the next frame
1795 // we composite should be considered an animation as well.
1796 mAnimCompositionPending = mAnimTransactionPending;
1797
Mathias Agopian4fec8732012-06-29 14:12:52 -07001798 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001799 mTransactionPending = false;
1800 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001801 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001802}
1803
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001805 const LayerVector& currentLayers, uint32_t layerStack,
1806 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001807{
Mathias Agopian841cde52012-03-01 15:44:37 -08001808 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001809 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001810
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001811 Region aboveOpaqueLayers;
1812 Region aboveCoveredLayers;
1813 Region dirty;
1814
Mathias Agopian87baae12012-07-31 12:38:26 -07001815 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001816
1817 size_t i = currentLayers.size();
1818 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001819 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001820
1821 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001822 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001823
Jesse Hall01e29052013-02-19 16:13:35 -08001824 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001825 if (s.layerStack != layerStack)
1826 continue;
1827
Mathias Agopianab028732010-03-16 16:41:46 -07001828 /*
1829 * opaqueRegion: area of a surface that is fully opaque.
1830 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001831 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001832
1833 /*
1834 * visibleRegion: area of a surface that is visible on screen
1835 * and not fully transparent. This is essentially the layer's
1836 * footprint minus the opaque regions above it.
1837 * Areas covered by a translucent surface are considered visible.
1838 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001839 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001840
1841 /*
1842 * coveredRegion: area of a surface that is covered by all
1843 * visible regions above it (which includes the translucent areas).
1844 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001845 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001846
Jesse Halla8026d22012-09-25 13:25:04 -07001847 /*
1848 * transparentRegion: area of a surface that is hinted to be completely
1849 * transparent. This is only used to tell when the layer has no visible
1850 * non-transparent regions and can be removed from the layer list. It
1851 * does not affect the visibleRegion of this layer or any layers
1852 * beneath it. The hint may not be correct if apps don't respect the
1853 * SurfaceView restrictions (which, sadly, some don't).
1854 */
1855 Region transparentRegion;
1856
Mathias Agopianab028732010-03-16 16:41:46 -07001857
1858 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001859 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001860 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001861 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001862 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001863 if (!visibleRegion.isEmpty()) {
1864 // Remove the transparent area from the visible region
1865 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001866 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001867 if (tr.preserveRects()) {
1868 // transform the transparent region
1869 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001870 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001871 // transformation too complex, can't do the
1872 // transparent region optimization.
1873 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001874 }
Mathias Agopianab028732010-03-16 16:41:46 -07001875 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001876
Mathias Agopianab028732010-03-16 16:41:46 -07001877 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001878 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001879 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001880 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1881 // the opaque region is the layer's footprint
1882 opaqueRegion = visibleRegion;
1883 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001884 }
1885 }
1886
Mathias Agopianab028732010-03-16 16:41:46 -07001887 // Clip the covered region to the visible region
1888 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1889
1890 // Update aboveCoveredLayers for next (lower) layer
1891 aboveCoveredLayers.orSelf(visibleRegion);
1892
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001893 // subtract the opaque region covered by the layers above us
1894 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001895
1896 // compute this layer's dirty region
1897 if (layer->contentDirty) {
1898 // we need to invalidate the whole region
1899 dirty = visibleRegion;
1900 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001901 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001902 layer->contentDirty = false;
1903 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001904 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001905 * the exposed region consists of two components:
1906 * 1) what's VISIBLE now and was COVERED before
1907 * 2) what's EXPOSED now less what was EXPOSED before
1908 *
1909 * note that (1) is conservative, we start with the whole
1910 * visible region but only keep what used to be covered by
1911 * something -- which mean it may have been exposed.
1912 *
1913 * (2) handles areas that were not covered by anything but got
1914 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001915 */
Mathias Agopianab028732010-03-16 16:41:46 -07001916 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001917 const Region oldVisibleRegion = layer->visibleRegion;
1918 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001919 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1920 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001921 }
1922 dirty.subtractSelf(aboveOpaqueLayers);
1923
1924 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001925 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001926
Mathias Agopianab028732010-03-16 16:41:46 -07001927 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001928 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001929
Jesse Halla8026d22012-09-25 13:25:04 -07001930 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001931 layer->setVisibleRegion(visibleRegion);
1932 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001933 layer->setVisibleNonTransparentRegion(
1934 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001935 }
1936
Mathias Agopian87baae12012-07-31 12:38:26 -07001937 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938}
1939
Mathias Agopian87baae12012-07-31 12:38:26 -07001940void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1941 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001942 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001943 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1944 if (hw->getLayerStack() == layerStack) {
1945 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001946 }
1947 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001948}
1949
Dan Stoza6b9454d2014-11-07 16:00:59 -08001950bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001951{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001952 ALOGV("handlePageFlip");
1953
Mathias Agopian4fec8732012-06-29 14:12:52 -07001954 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001955
Mathias Agopian4fec8732012-06-29 14:12:52 -07001956 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001957 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001958 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001959
1960 // Store the set of layers that need updates. This set must not change as
1961 // buffers are being latched, as this could result in a deadlock.
1962 // Example: Two producers share the same command stream and:
1963 // 1.) Layer 0 is latched
1964 // 2.) Layer 0 gets a new frame
1965 // 2.) Layer 1 gets a new frame
1966 // 3.) Layer 1 is latched.
1967 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1968 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001969 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001970 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001971 if (layer->hasQueuedFrame()) {
1972 frameQueued = true;
1973 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001975 } else {
1976 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001977 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001978 } else {
1979 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001980 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001981 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001983 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001984 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001985 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001986 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001987 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001988
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001989 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001990
1991 // If we will need to wake up at some time in the future to deal with a
1992 // queued frame that shouldn't be displayed during this vsync period, wake
1993 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001994 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001995 signalLayerUpdate();
1996 }
1997
1998 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002000}
2001
Mathias Agopianad456f92011-01-13 17:53:01 -08002002void SurfaceFlinger::invalidateHwcGeometry()
2003{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002005}
2006
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002007
Mathias Agopiancd60f992012-08-16 16:28:27 -07002008void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002009 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002010{
Dan Stoza71433162014-02-04 16:22:36 -08002011 // We only need to actually compose the display if:
2012 // 1) It is being handled by hardware composer, which may need this to
2013 // keep its virtual display state machine in sync, or
2014 // 2) There is work to be done (the dirty region isn't empty)
2015 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2016 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002017 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002018 return;
2019 }
2020
Dan Stoza9e56aa02015-11-02 13:00:03 -08002021 ALOGV("doDisplayComposition");
2022
Mathias Agopian87baae12012-07-31 12:38:26 -07002023 Region dirtyRegion(inDirtyRegion);
2024
Mathias Agopianb8a55602009-06-26 19:06:36 -07002025 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002026 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002027
Mathias Agopian42977342012-08-05 00:40:46 -07002028 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002029 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002030 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2031 // takes a rectangle, we must make sure to update that whole
2032 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002033 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002034 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002035 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002036 // We need to redraw the rectangle that will be updated
2037 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002038 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002039 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002040 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002041 } else {
2042 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002043 dirtyRegion.set(hw->bounds());
2044 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002045 }
2046 }
2047
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002048 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002049
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002050 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002051 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002052
2053 // swap buffers (presentation)
2054 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002055}
2056
Dan Stoza9e56aa02015-11-02 13:00:03 -08002057bool SurfaceFlinger::doComposeSurfaces(
2058 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002059{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002060 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002061
Dan Stoza9e56aa02015-11-02 13:00:03 -08002062 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002063
2064 mat4 oldColorMatrix;
2065 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2066 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2067 if (applyColorMatrix) {
2068 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2069 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2070 }
2071
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2073 if (hasClientComposition) {
2074 ALOGV("hasClientComposition");
2075
2076 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002077 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002079 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2080 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2081 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2082 }
2083 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002084 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002085
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002086 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002087 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2088 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002089 // when using overlays, we assume a fully transparent framebuffer
2090 // NOTE: we could reduce how much we need to clear, for instance
2091 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002092 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002093 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002094 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002095 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002096 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002097 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002098
2099 // we remove the scissor part
2100 // we're left with the letterbox region
2101 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002102 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002103
2104 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002105 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002106
2107 // but limit it to the dirty region
2108 region.andSelf(dirty);
2109
Mathias Agopianb9494d52012-04-18 02:28:45 -07002110 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002111 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002112 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002113 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002114 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002115 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002116
Dan Stoza9e56aa02015-11-02 13:00:03 -08002117 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002118 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002119 // scissor on the main display. It should never be needed
2120 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002121 const Rect& bounds(displayDevice->getBounds());
2122 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002123 if (scissor != bounds) {
2124 // scissor doesn't match the screen's dimensions, so we
2125 // need to clear everything outside of it and enable
2126 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002127
Mathias Agopianf45c5102012-10-24 16:29:17 -07002128 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002129 const uint32_t height = displayDevice->getHeight();
2130 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002131 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002132 }
2133 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002134 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002135
Mathias Agopian85d751c2012-08-29 16:59:24 -07002136 /*
2137 * and then, render the layers targeted at the framebuffer
2138 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002139
Dan Stoza9e56aa02015-11-02 13:00:03 -08002140 ALOGV("Rendering client layers");
2141 const Transform& displayTransform = displayDevice->getTransform();
2142 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002143 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002144 bool firstLayer = true;
2145 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2146 const Region clip(dirty.intersect(
2147 displayTransform.transform(layer->visibleRegion)));
2148 ALOGV("Layer: %s", layer->getName().string());
2149 ALOGV(" Composition type: %s",
2150 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002151 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002152 switch (layer->getCompositionType(hwcId)) {
2153 case HWC2::Composition::Cursor:
2154 case HWC2::Composition::Device:
2155 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002156 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002157 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2158 layer->isOpaque(state) && (state.alpha == 1.0f)
2159 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002160 // never clear the very first layer since we're
2161 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002162 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002163 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002164 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002165 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002166 case HWC2::Composition::Client: {
2167 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002168 break;
2169 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002171 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002172 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002173 } else {
2174 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002175 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002176 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002177 }
2178 } else {
2179 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002181 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002182 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002183 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002184 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002185 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002186 }
2187 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002188
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002189 if (applyColorMatrix) {
2190 getRenderEngine().setupColorTransform(oldColorMatrix);
2191 }
2192
Mathias Agopianf45c5102012-10-24 16:29:17 -07002193 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002195 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002196}
2197
Mathias Agopian3f844832013-08-07 21:24:32 -07002198void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002199 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002200 RenderEngine& engine(getRenderEngine());
2201 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002202}
2203
Dan Stoza7d89d062015-04-30 13:29:25 -07002204status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002205 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002206 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002207 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002208{
Dan Stoza7d89d062015-04-30 13:29:25 -07002209 // add this layer to the current state list
2210 {
2211 Mutex::Autolock _l(mStateLock);
2212 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2213 return NO_MEMORY;
2214 }
2215 mCurrentState.layersSortedByZ.add(lbc);
2216 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2217 }
2218
Mathias Agopian96f08192010-06-02 23:28:45 -07002219 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002220 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002221
Dan Stoza7d89d062015-04-30 13:29:25 -07002222 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002223}
2224
Dan Stoza92cd24e2016-08-09 13:21:03 -07002225status_t SurfaceFlinger::removeLayer(const wp<Layer>& weakLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002226 Mutex::Autolock _l(mStateLock);
Dan Stoza92cd24e2016-08-09 13:21:03 -07002227 sp<Layer> layer = weakLayer.promote();
2228 if (layer == nullptr) {
2229 // The layer has already been removed, carry on
2230 return NO_ERROR;
2231 }
2232
Mathias Agopian13127d82013-03-05 17:47:11 -08002233 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002234 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002235 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002236 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002237 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002238 return NO_ERROR;
2239 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002240 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002241}
2242
Dan Stozac7014012014-02-14 15:03:43 -08002243uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002244 return android_atomic_release_load(&mTransactionFlags);
2245}
2246
Mathias Agopian3f844832013-08-07 21:24:32 -07002247uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002248 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2249}
2250
Mathias Agopian3f844832013-08-07 21:24:32 -07002251uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002252 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2253 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002254 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002255 }
2256 return old;
2257}
2258
Mathias Agopian8b33f032012-07-24 20:43:54 -07002259void SurfaceFlinger::setTransactionState(
2260 const Vector<ComposerState>& state,
2261 const Vector<DisplayState>& displays,
2262 uint32_t flags)
2263{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002264 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002265 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002266 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002267
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002268 if (flags & eAnimation) {
2269 // For window updates that are part of an animation we must wait for
2270 // previous animation "frames" to be handled.
2271 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002272 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002273 if (CC_UNLIKELY(err != NO_ERROR)) {
2274 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002275 // caller after a few seconds.
2276 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2277 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002278 mAnimTransactionPending = false;
2279 break;
2280 }
2281 }
2282 }
2283
Mathias Agopiane57f2922012-08-09 16:29:12 -07002284 size_t count = displays.size();
2285 for (size_t i=0 ; i<count ; i++) {
2286 const DisplayState& s(displays[i]);
2287 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002288 }
2289
Mathias Agopiane57f2922012-08-09 16:29:12 -07002290 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002291 for (size_t i=0 ; i<count ; i++) {
2292 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002293 // Here we need to check that the interface we're given is indeed
2294 // one of our own. A malicious client could give us a NULL
2295 // IInterface, or one of its own or even one of our own but a
2296 // different type. All these situations would cause us to crash.
2297 //
2298 // NOTE: it would be better to use RTTI as we could directly check
2299 // that we have a Client*. however, RTTI is disabled in Android.
2300 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002301 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002302 if (binder != NULL) {
2303 String16 desc(binder->getInterfaceDescriptor());
2304 if (desc == ISurfaceComposerClient::descriptor) {
2305 sp<Client> client( static_cast<Client *>(s.client.get()) );
2306 transactionFlags |= setClientStateLocked(client, s.state);
2307 }
2308 }
2309 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002310 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002311
Robert Carr2a7dbb42016-05-24 11:41:28 -07002312 // If a synchronous transaction is explicitly requested without any changes,
2313 // force a transaction anyway. This can be used as a flush mechanism for
2314 // previous async transactions.
2315 if (transactionFlags == 0 && (flags & eSynchronous)) {
2316 transactionFlags = eTransactionNeeded;
2317 }
2318
Mathias Agopian386aa982011-11-07 21:58:03 -08002319 if (transactionFlags) {
2320 // this triggers the transaction
2321 setTransactionFlags(transactionFlags);
2322
2323 // if this is a synchronous transaction, wait for it to take effect
2324 // before returning.
2325 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002326 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002327 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002328 if (flags & eAnimation) {
2329 mAnimTransactionPending = true;
2330 }
2331 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002332 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2333 if (CC_UNLIKELY(err != NO_ERROR)) {
2334 // just in case something goes wrong in SF, return to the
2335 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002336 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2337 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002338 break;
2339 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002340 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 }
2342}
2343
Mathias Agopiane57f2922012-08-09 16:29:12 -07002344uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2345{
Jesse Hall9a143922012-10-04 16:29:19 -07002346 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2347 if (dpyIdx < 0)
2348 return 0;
2349
Mathias Agopiane57f2922012-08-09 16:29:12 -07002350 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002351 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002352 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002353 const uint32_t what = s.what;
2354 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002355 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002356 disp.surface = s.surface;
2357 flags |= eDisplayTransactionNeeded;
2358 }
2359 }
2360 if (what & DisplayState::eLayerStackChanged) {
2361 if (disp.layerStack != s.layerStack) {
2362 disp.layerStack = s.layerStack;
2363 flags |= eDisplayTransactionNeeded;
2364 }
2365 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002366 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002367 if (disp.orientation != s.orientation) {
2368 disp.orientation = s.orientation;
2369 flags |= eDisplayTransactionNeeded;
2370 }
2371 if (disp.frame != s.frame) {
2372 disp.frame = s.frame;
2373 flags |= eDisplayTransactionNeeded;
2374 }
2375 if (disp.viewport != s.viewport) {
2376 disp.viewport = s.viewport;
2377 flags |= eDisplayTransactionNeeded;
2378 }
2379 }
Michael Lentine47e45402014-07-18 15:34:25 -07002380 if (what & DisplayState::eDisplaySizeChanged) {
2381 if (disp.width != s.width) {
2382 disp.width = s.width;
2383 flags |= eDisplayTransactionNeeded;
2384 }
2385 if (disp.height != s.height) {
2386 disp.height = s.height;
2387 flags |= eDisplayTransactionNeeded;
2388 }
2389 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002390 }
2391 return flags;
2392}
2393
2394uint32_t SurfaceFlinger::setClientStateLocked(
2395 const sp<Client>& client,
2396 const layer_state_t& s)
2397{
2398 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002399 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 if (layer != 0) {
2401 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002402 bool geometryAppliesWithResize =
2403 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002404 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002405 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002406 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002407 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002408 }
2409 if (what & layer_state_t::eLayerChanged) {
2410 // NOTE: index needs to be calculated before we update the state
2411 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002412 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002413 mCurrentState.layersSortedByZ.removeAt(idx);
2414 mCurrentState.layersSortedByZ.add(layer);
2415 // we need traversal (state changed)
2416 // AND transaction (list changed)
2417 flags |= eTransactionNeeded|eTraversalNeeded;
2418 }
2419 }
2420 if (what & layer_state_t::eSizeChanged) {
2421 if (layer->setSize(s.w, s.h)) {
2422 flags |= eTraversalNeeded;
2423 }
2424 }
2425 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002426 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002427 flags |= eTraversalNeeded;
2428 }
2429 if (what & layer_state_t::eMatrixChanged) {
2430 if (layer->setMatrix(s.matrix))
2431 flags |= eTraversalNeeded;
2432 }
2433 if (what & layer_state_t::eTransparentRegionChanged) {
2434 if (layer->setTransparentRegionHint(s.transparentRegion))
2435 flags |= eTraversalNeeded;
2436 }
Dan Stoza23116082015-06-18 14:58:39 -07002437 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002438 if (layer->setFlags(s.flags, s.mask))
2439 flags |= eTraversalNeeded;
2440 }
2441 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002442 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002443 flags |= eTraversalNeeded;
2444 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002445 if (what & layer_state_t::eFinalCropChanged) {
2446 if (layer->setFinalCrop(s.finalCrop))
2447 flags |= eTraversalNeeded;
2448 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002449 if (what & layer_state_t::eLayerStackChanged) {
2450 // NOTE: index needs to be calculated before we update the state
2451 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002452 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002453 mCurrentState.layersSortedByZ.removeAt(idx);
2454 mCurrentState.layersSortedByZ.add(layer);
2455 // we need traversal (state changed)
2456 // AND transaction (list changed)
2457 flags |= eTransactionNeeded|eTraversalNeeded;
2458 }
2459 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002460 if (what & layer_state_t::eDeferTransaction) {
2461 layer->deferTransactionUntil(s.handle, s.frameNumber);
2462 // We don't trigger a traversal here because if no other state is
2463 // changed, we don't want this to cause any more work
2464 }
Robert Carrc3574f72016-03-24 12:19:32 -07002465 if (what & layer_state_t::eOverrideScalingModeChanged) {
2466 layer->setOverrideScalingMode(s.overrideScalingMode);
2467 // We don't trigger a traversal here because if no other state is
2468 // changed, we don't want this to cause any more work
2469 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002470 }
2471 return flags;
2472}
2473
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002474status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002475 const String8& name,
2476 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002477 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2478 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002480 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002481 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002482 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002483 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002484 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002485 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002486
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002487 status_t result = NO_ERROR;
2488
2489 sp<Layer> layer;
2490
Mathias Agopian3165cc22012-08-08 19:42:09 -07002491 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2492 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002493 result = createNormalLayer(client,
2494 name, w, h, flags, format,
2495 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002497 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002498 result = createDimLayer(client,
2499 name, w, h, flags,
2500 handle, gbp, &layer);
2501 break;
2502 default:
2503 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 break;
2505 }
2506
Dan Stoza7d89d062015-04-30 13:29:25 -07002507 if (result != NO_ERROR) {
2508 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002509 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002510
2511 result = addClientLayer(client, *handle, *gbp, layer);
2512 if (result != NO_ERROR) {
2513 return result;
2514 }
2515
2516 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002517 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002518}
2519
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002520status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2521 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2522 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002523{
2524 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002525 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526 case PIXEL_FORMAT_TRANSPARENT:
2527 case PIXEL_FORMAT_TRANSLUCENT:
2528 format = PIXEL_FORMAT_RGBA_8888;
2529 break;
2530 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002531 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002532 break;
2533 }
2534
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002535 *outLayer = new Layer(this, client, name, w, h, flags);
2536 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2537 if (err == NO_ERROR) {
2538 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002539 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002541
2542 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2543 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002544}
2545
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002546status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2547 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2548 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002549{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002550 *outLayer = new LayerDim(this, client, name, w, h, flags);
2551 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002552 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002553 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002554}
2555
Mathias Agopianac9fa422013-02-11 16:40:36 -08002556status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557{
Mathias Agopian67106042013-03-14 19:18:13 -07002558 // called by the window manager when it wants to remove a Layer
2559 status_t err = NO_ERROR;
2560 sp<Layer> l(client->getLayerUser(handle));
2561 if (l != NULL) {
2562 err = removeLayer(l);
2563 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2564 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002565 }
2566 return err;
2567}
2568
Mathias Agopian13127d82013-03-05 17:47:11 -08002569status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002570{
Mathias Agopian67106042013-03-14 19:18:13 -07002571 // called by ~LayerCleaner() when all references to the IBinder (handle)
2572 // are gone
Dan Stoza92cd24e2016-08-09 13:21:03 -07002573 return removeLayer(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002574}
2575
Mathias Agopianb60314a2012-04-10 22:09:54 -07002576// ---------------------------------------------------------------------------
2577
Andy McFadden13a082e2012-08-24 10:16:42 -07002578void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002579 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002580 Vector<ComposerState> state;
2581 Vector<DisplayState> displays;
2582 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002583 d.what = DisplayState::eDisplayProjectionChanged |
2584 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002585 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002586 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002587 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002588 d.frame.makeInvalid();
2589 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002590 d.width = 0;
2591 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002592 displays.add(d);
2593 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002594 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002595
Dan Stoza9e56aa02015-11-02 13:00:03 -08002596 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2597 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002598 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002599}
2600
2601void SurfaceFlinger::initializeDisplays() {
2602 class MessageScreenInitialized : public MessageBase {
2603 SurfaceFlinger* flinger;
2604 public:
2605 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2606 virtual bool handler() {
2607 flinger->onInitializeDisplays();
2608 return true;
2609 }
2610 };
2611 sp<MessageBase> msg = new MessageScreenInitialized(this);
2612 postMessageAsync(msg); // we may be called from main thread, use async message
2613}
2614
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002615void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2616 int mode) {
2617 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2618 this);
2619 int32_t type = hw->getDisplayType();
2620 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002621
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002622 if (mode == currentMode) {
2623 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002624 return;
2625 }
2626
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002627 hw->setPowerMode(mode);
2628 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2629 ALOGW("Trying to set power mode for virtual display");
2630 return;
2631 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002632
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002633 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002634 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002635 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002636 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2637 // FIXME: eventthread only knows about the main display right now
2638 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002639 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002640 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002641
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002642 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002643 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002644 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07002645
2646 struct sched_param param = {0};
2647 param.sched_priority = 1;
2648 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
2649 ALOGW("Couldn't set SCHED_FIFO on display on");
2650 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002651 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07002652 // Turn off the display
2653 struct sched_param param = {0};
2654 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
2655 ALOGW("Couldn't set SCHED_OTHER on display off");
2656 }
2657
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002658 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002659 disableHardwareVsync(true); // also cancels any in-progress resync
2660
Mathias Agopiancde87a32012-09-13 14:09:01 -07002661 // FIXME: eventthread only knows about the main display right now
2662 mEventThread->onScreenReleased();
2663 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002664
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002665 getHwComposer().setPowerMode(type, mode);
2666 mVisibleRegionsDirty = true;
2667 // from this point on, SF will stop drawing on this display
2668 } else {
2669 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002670 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002671}
2672
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002673void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2674 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002675 SurfaceFlinger& mFlinger;
2676 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002677 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002678 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002679 MessageSetPowerMode(SurfaceFlinger& flinger,
2680 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2681 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002682 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002683 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002684 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002685 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002686 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002687 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002688 ALOGW("Attempt to set power mode = %d for virtual display",
2689 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002690 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002691 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002692 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002693 return true;
2694 }
2695 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002696 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002697 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002698}
2699
2700// ---------------------------------------------------------------------------
2701
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2703{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002704 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002705
Mathias Agopianbd115332013-04-18 16:41:04 -07002706 IPCThreadState* ipc = IPCThreadState::self();
2707 const int pid = ipc->getCallingPid();
2708 const int uid = ipc->getCallingUid();
2709 if ((uid != AID_SHELL) &&
2710 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002711 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002712 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002713 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002714 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002715 // (this would indicate SF is stuck, but we want to be able to
2716 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002717 status_t err = mStateLock.timedLock(s2ns(1));
2718 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002719 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002720 result.appendFormat(
2721 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2722 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002723 }
2724
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002725 bool dumpAll = true;
2726 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002727 size_t numArgs = args.size();
2728 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002729 if ((index < numArgs) &&
2730 (args[index] == String16("--list"))) {
2731 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002732 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002733 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002734 }
2735
2736 if ((index < numArgs) &&
2737 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002738 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002739 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002740 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002741 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002742
2743 if ((index < numArgs) &&
2744 (args[index] == String16("--latency-clear"))) {
2745 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002746 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002747 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002748 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002749
2750 if ((index < numArgs) &&
2751 (args[index] == String16("--dispsync"))) {
2752 index++;
2753 mPrimaryDispSync.dump(result);
2754 dumpAll = false;
2755 }
Dan Stozab90cf072015-03-05 11:05:59 -08002756
2757 if ((index < numArgs) &&
2758 (args[index] == String16("--static-screen"))) {
2759 index++;
2760 dumpStaticScreenStats(result);
2761 dumpAll = false;
2762 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002763
2764 if ((index < numArgs) &&
2765 (args[index] == String16("--fences"))) {
2766 index++;
2767 mFenceTracker.dump(&result);
2768 dumpAll = false;
2769 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002770 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002771
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002772 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002773 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002774 }
2775
Mathias Agopian9795c422009-08-26 16:36:26 -07002776 if (locked) {
2777 mStateLock.unlock();
2778 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002779 }
2780 write(fd, result.string(), result.size());
2781 return NO_ERROR;
2782}
2783
Dan Stozac7014012014-02-14 15:03:43 -08002784void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2785 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002786{
2787 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2788 const size_t count = currentLayers.size();
2789 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002790 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002791 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002792 }
2793}
2794
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002795void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002796 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002797{
2798 String8 name;
2799 if (index < args.size()) {
2800 name = String8(args[index]);
2801 index++;
2802 }
2803
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2805 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002806 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002807
2808 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002809 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002810 } else {
2811 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2812 const size_t count = currentLayers.size();
2813 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002814 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002815 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002816 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002817 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002818 }
2819 }
2820}
2821
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002822void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002823 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002824{
2825 String8 name;
2826 if (index < args.size()) {
2827 name = String8(args[index]);
2828 index++;
2829 }
2830
2831 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2832 const size_t count = currentLayers.size();
2833 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002834 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002835 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002836 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002837 }
2838 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002839
Svetoslavd85084b2014-03-20 10:28:31 -07002840 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002841}
2842
Jamie Gennis6547ff42013-07-16 20:12:42 -07002843// This should only be called from the main thread. Otherwise it would need
2844// the lock and should use mCurrentState rather than mDrawingState.
2845void SurfaceFlinger::logFrameStats() {
2846 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2847 const size_t count = drawingLayers.size();
2848 for (size_t i=0 ; i<count ; i++) {
2849 const sp<Layer>& layer(drawingLayers[i]);
2850 layer->logFrameStats();
2851 }
2852
2853 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2854}
2855
Andy McFadden4803b742012-09-24 19:07:20 -07002856/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2857{
2858 static const char* config =
2859 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002860#ifdef HAS_CONTEXT_PRIORITY
2861 " HAS_CONTEXT_PRIORITY"
2862#endif
2863#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2864 " NEVER_DEFAULT_TO_ASYNC_MODE"
2865#endif
2866#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2867 " TARGET_DISABLE_TRIPLE_BUFFERING"
2868#endif
2869 "]";
2870 result.append(config);
2871}
2872
Dan Stozab90cf072015-03-05 11:05:59 -08002873void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2874{
2875 result.appendFormat("Static screen stats:\n");
2876 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2877 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2878 float percent = 100.0f *
2879 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2880 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2881 b + 1, bucketTimeSec, percent);
2882 }
2883 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2884 float percent = 100.0f *
2885 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2886 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2887 NUM_BUCKETS - 1, bucketTimeSec, percent);
2888}
2889
Dan Stozae77c7662016-05-13 11:37:28 -07002890void SurfaceFlinger::recordBufferingStats(const char* layerName,
2891 std::vector<OccupancyTracker::Segment>&& history) {
2892 Mutex::Autolock lock(mBufferingStatsMutex);
2893 auto& stats = mBufferingStats[layerName];
2894 for (const auto& segment : history) {
2895 if (!segment.usedThirdBuffer) {
2896 stats.twoBufferTime += segment.totalTime;
2897 }
2898 if (segment.occupancyAverage < 1.0f) {
2899 stats.doubleBufferedTime += segment.totalTime;
2900 } else if (segment.occupancyAverage < 2.0f) {
2901 stats.tripleBufferedTime += segment.totalTime;
2902 }
2903 ++stats.numSegments;
2904 stats.totalTime += segment.totalTime;
2905 }
2906}
2907
2908void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2909 result.append("Buffering stats:\n");
2910 result.append(" [Layer name] <Active time> <Two buffer> "
2911 "<Double buffered> <Triple buffered>\n");
2912 Mutex::Autolock lock(mBufferingStatsMutex);
2913 typedef std::tuple<std::string, float, float, float> BufferTuple;
2914 std::map<float, BufferTuple, std::greater<float>> sorted;
2915 for (const auto& statsPair : mBufferingStats) {
2916 const char* name = statsPair.first.c_str();
2917 const BufferingStats& stats = statsPair.second;
2918 if (stats.numSegments == 0) {
2919 continue;
2920 }
2921 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2922 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2923 stats.totalTime;
2924 float doubleBufferRatio = static_cast<float>(
2925 stats.doubleBufferedTime) / stats.totalTime;
2926 float tripleBufferRatio = static_cast<float>(
2927 stats.tripleBufferedTime) / stats.totalTime;
2928 sorted.insert({activeTime, {name, twoBufferRatio,
2929 doubleBufferRatio, tripleBufferRatio}});
2930 }
2931 for (const auto& sortedPair : sorted) {
2932 float activeTime = sortedPair.first;
2933 const BufferTuple& values = sortedPair.second;
2934 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2935 std::get<0>(values).c_str(), activeTime,
2936 std::get<1>(values), std::get<2>(values),
2937 std::get<3>(values));
2938 }
2939 result.append("\n");
2940}
2941
2942
Mathias Agopian74d211a2013-04-22 16:55:35 +02002943void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2944 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002945{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002946 bool colorize = false;
2947 if (index < args.size()
2948 && (args[index] == String16("--color"))) {
2949 colorize = true;
2950 index++;
2951 }
2952
2953 Colorizer colorizer(colorize);
2954
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002955 // figure out if we're stuck somewhere
2956 const nsecs_t now = systemTime();
2957 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2958 const nsecs_t inTransaction(mDebugInTransaction);
2959 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2960 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2961
2962 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002963 * Dump library configuration.
2964 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002965
2966 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002967 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002968 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002969 appendSfConfigString(result);
2970 appendUiConfigString(result);
2971 appendGuiConfigString(result);
2972 result.append("\n");
2973
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002974 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002975 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002976 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002977 result.append(SyncFeatures::getInstance().toString());
2978 result.append("\n");
2979
Dan Stoza9e56aa02015-11-02 13:00:03 -08002980 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2981
Andy McFadden41d67d72014-04-25 16:58:34 -07002982 colorizer.bold(result);
2983 result.append("DispSync configuration: ");
2984 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002985 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2986 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002987 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2988 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002989 result.append("\n");
2990
Dan Stozab90cf072015-03-05 11:05:59 -08002991 // Dump static screen stats
2992 result.append("\n");
2993 dumpStaticScreenStats(result);
2994 result.append("\n");
2995
Dan Stozae77c7662016-05-13 11:37:28 -07002996 dumpBufferingStats(result);
2997
Andy McFadden4803b742012-09-24 19:07:20 -07002998 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002999 * Dump the visible layer list
3000 */
3001 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3002 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003003 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003004 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003005 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003006 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003007 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003008 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003009 }
3010
3011 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003012 * Dump Display state
3013 */
3014
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003015 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003016 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003017 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003018 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3019 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003020 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003021 }
3022
3023 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003024 * Dump SurfaceFlinger global state
3025 */
3026
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003027 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003028 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003029 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003030
Mathias Agopian888c8222012-08-04 21:10:38 -07003031 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003032 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003033
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003034 colorizer.bold(result);
3035 result.appendFormat("EGL implementation : %s\n",
3036 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3037 colorizer.reset(result);
3038 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003039 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003040
Mathias Agopian875d8e12013-06-07 15:35:48 -07003041 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003042
Mathias Agopian42977342012-08-05 00:40:46 -07003043 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003044 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3045 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003046 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003047 " last eglSwapBuffers() time: %f us\n"
3048 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003049 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003050 " refresh-rate : %f fps\n"
3051 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003052 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003053 " gpu_to_cpu_unsupported : %d\n"
3054 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003055 mLastSwapBufferTime/1000.0,
3056 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003057 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003058 1e9 / activeConfig->getVsyncPeriod(),
3059 activeConfig->getDpiX(),
3060 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003061 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003062
Mathias Agopian74d211a2013-04-22 16:55:35 +02003063 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003064 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003065
Mathias Agopian74d211a2013-04-22 16:55:35 +02003066 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003067 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003068
3069 /*
3070 * VSYNC state
3071 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003072 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07003073 result.append("\n");
3074
3075 /*
3076 * HWC layer minidump
3077 */
3078 for (size_t d = 0; d < mDisplays.size(); d++) {
3079 const sp<const DisplayDevice>& displayDevice(mDisplays[d]);
3080 int32_t hwcId = displayDevice->getHwcDisplayId();
3081 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
3082 continue;
3083 }
3084
3085 result.appendFormat("Display %d HWC layers:\n", hwcId);
3086 Layer::miniDumpHeader(result);
3087 for (size_t l = 0; l < count; l++) {
3088 const sp<Layer>& layer(currentLayers[l]);
3089 layer->miniDump(result, hwcId);
3090 }
3091 result.append("\n");
3092 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003093
3094 /*
3095 * Dump HWComposer state
3096 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003097 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003098 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003099 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003100 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003101 result.appendFormat(" h/w composer %s\n",
3102 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003103 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003104
3105 /*
3106 * Dump gralloc state
3107 */
3108 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3109 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003110}
3111
Mathias Agopian13127d82013-03-05 17:47:11 -08003112const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003113SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003114 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003115 wp<IBinder> dpy;
3116 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3117 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3118 dpy = mDisplays.keyAt(i);
3119 break;
3120 }
3121 }
3122 if (dpy == NULL) {
3123 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3124 // Just use the primary display so we have something to return
3125 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3126 }
3127 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003128}
3129
Keun young Park63f165f2012-08-31 10:53:36 -07003130bool SurfaceFlinger::startDdmConnection()
3131{
3132 void* libddmconnection_dso =
3133 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3134 if (!libddmconnection_dso) {
3135 return false;
3136 }
3137 void (*DdmConnection_start)(const char* name);
3138 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003139 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003140 if (!DdmConnection_start) {
3141 dlclose(libddmconnection_dso);
3142 return false;
3143 }
3144 (*DdmConnection_start)(getServiceName());
3145 return true;
3146}
3147
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003148status_t SurfaceFlinger::onTransact(
3149 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3150{
3151 switch (code) {
3152 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003153 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003154 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003155 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003156 case CLEAR_ANIMATION_FRAME_STATS:
3157 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003158 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003159 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003160 {
3161 // codes that require permission check
3162 IPCThreadState* ipc = IPCThreadState::self();
3163 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003164 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003165 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003166 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003167 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003168 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3169 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003170 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003171 break;
3172 }
3173 case CAPTURE_SCREEN:
3174 {
3175 // codes that require permission check
3176 IPCThreadState* ipc = IPCThreadState::self();
3177 const int pid = ipc->getCallingPid();
3178 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003179 if ((uid != AID_GRAPHICS) &&
3180 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003181 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003182 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3183 return PERMISSION_DENIED;
3184 }
3185 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186 }
3187 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003188
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003189 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3190 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003191 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003192 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003193 IPCThreadState* ipc = IPCThreadState::self();
3194 const int pid = ipc->getCallingPid();
3195 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003196 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003197 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003198 return PERMISSION_DENIED;
3199 }
3200 int n;
3201 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003202 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003203 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 return NO_ERROR;
3205 case 1002: // SHOW_UPDATES
3206 n = data.readInt32();
3207 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003208 invalidateHwcGeometry();
3209 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003212 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003213 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003215 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003216 setTransactionFlags(
3217 eTransactionNeeded|
3218 eDisplayTransactionNeeded|
3219 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003220 return NO_ERROR;
3221 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003222 case 1006:{ // send empty update
3223 signalRefresh();
3224 return NO_ERROR;
3225 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003226 case 1008: // toggle use of hw composer
3227 n = data.readInt32();
3228 mDebugDisableHWC = n ? 1 : 0;
3229 invalidateHwcGeometry();
3230 repaintEverything();
3231 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003232 case 1009: // toggle use of transform hint
3233 n = data.readInt32();
3234 mDebugDisableTransformHint = n ? 1 : 0;
3235 invalidateHwcGeometry();
3236 repaintEverything();
3237 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003239 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 reply->writeInt32(0);
3241 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003242 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003243 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 return NO_ERROR;
3245 case 1013: {
3246 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003247 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3248 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003249 return NO_ERROR;
3250 }
3251 case 1014: {
3252 // daltonize
3253 n = data.readInt32();
3254 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003255 case 1:
3256 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3257 break;
3258 case 2:
3259 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3260 break;
3261 case 3:
3262 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3263 break;
3264 default:
3265 mDaltonizer.setType(ColorBlindnessType::None);
3266 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003267 }
3268 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003269 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003270 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003271 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003272 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003273 invalidateHwcGeometry();
3274 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003275 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003276 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003277 case 1015: {
3278 // apply a color matrix
3279 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003280 if (n) {
3281 // color matrix is sent as mat3 matrix followed by vec3
3282 // offset, then packed into a mat4 where the last row is
3283 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003284 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003285 for (size_t j = 0; j < 4; j++) {
3286 mColorMatrix[i][j] = data.readFloat();
3287 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003288 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003289 } else {
3290 mColorMatrix = mat4();
3291 }
3292 invalidateHwcGeometry();
3293 repaintEverything();
3294 return NO_ERROR;
3295 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003296 // This is an experimental interface
3297 // Needs to be shifted to proper binder interface when we productize
3298 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003299 n = data.readInt32();
3300 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003301 return NO_ERROR;
3302 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003303 case 1017: {
3304 n = data.readInt32();
3305 mForceFullDamage = static_cast<bool>(n);
3306 return NO_ERROR;
3307 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003308 case 1018: { // Modify Choreographer's phase offset
3309 n = data.readInt32();
3310 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3311 return NO_ERROR;
3312 }
3313 case 1019: { // Modify SurfaceFlinger's phase offset
3314 n = data.readInt32();
3315 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3316 return NO_ERROR;
3317 }
Dan Stoza3cf4bfe2016-08-02 10:27:31 -07003318 case 1021: { // Disable HWC virtual displays
3319 n = data.readInt32();
3320 mUseHwcVirtualDisplays = !n;
3321 return NO_ERROR;
3322 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 }
3324 }
3325 return err;
3326}
3327
Mathias Agopian53331da2011-08-22 21:44:41 -07003328void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003329 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003330 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003331}
3332
Mathias Agopian59119e62010-10-11 12:37:43 -07003333// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003334// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003335// ---------------------------------------------------------------------------
3336
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003337/* The code below is here to handle b/8734824
3338 *
3339 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003340 * from the surfaceflinger thread to the calling binder thread, where they
3341 * are executed. This allows the calling thread in the calling process to be
3342 * reused and not depend on having "enough" binder threads to handle the
3343 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003344 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003345class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003346 /* Parts of GraphicProducerWrapper are run on two different threads,
3347 * communicating by sending messages via Looper but also by shared member
3348 * data. Coherence maintenance is subtle and in places implicit (ugh).
3349 *
3350 * Don't rely on Looper's sendMessage/handleMessage providing
3351 * release/acquire semantics for any data not actually in the Message.
3352 * Data going from surfaceflinger to binder threads needs to be
3353 * synchronized explicitly.
3354 *
3355 * Barrier open/wait do provide release/acquire semantics. This provides
3356 * implicit synchronization for data coming back from binder to
3357 * surfaceflinger threads.
3358 */
3359
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003360 sp<IGraphicBufferProducer> impl;
3361 sp<Looper> looper;
3362 status_t result;
3363 bool exitPending;
3364 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003365 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003366 uint32_t code;
3367 Parcel const* data;
3368 Parcel* reply;
3369
3370 enum {
3371 MSG_API_CALL,
3372 MSG_EXIT
3373 };
3374
3375 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003376 * Called on surfaceflinger thread. This is called by our "fake"
3377 * BpGraphicBufferProducer. We package the data and reply Parcel and
3378 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003379 */
3380 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003381 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003382 this->code = code;
3383 this->data = &data;
3384 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003385 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003386 // if we've exited, we run the message synchronously right here.
3387 // note (JH): as far as I can tell from looking at the code, this
3388 // never actually happens. if it does, i'm not sure if it happens
3389 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003390 handleMessage(Message(MSG_API_CALL));
3391 } else {
3392 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003393 // Prevent stores to this->{code, data, reply} from being
3394 // reordered later than the construction of Message.
3395 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003396 looper->sendMessage(this, Message(MSG_API_CALL));
3397 barrier.wait();
3398 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003399 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003400 }
3401
3402 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003403 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003404 * call the real BpGraphicBufferProducer.
3405 */
3406 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003407 int what = message.what;
3408 // Prevent reads below from happening before the read from Message
3409 atomic_thread_fence(memory_order_acquire);
3410 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003411 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003412 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003413 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003414 exitRequested = true;
3415 }
3416 }
3417
3418public:
Jesse Hallb154c422014-07-13 12:47:02 -07003419 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3420 : impl(impl),
3421 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003422 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003423 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003424 exitRequested(false),
3425 code(0),
3426 data(NULL),
3427 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003428 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003429
Jesse Hallb154c422014-07-13 12:47:02 -07003430 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003431 status_t waitForResponse() {
3432 do {
3433 looper->pollOnce(-1);
3434 } while (!exitRequested);
3435 return result;
3436 }
3437
Jesse Hallb154c422014-07-13 12:47:02 -07003438 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003439 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003440 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003441 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003442 // Ensure this->result is visible to the binder thread before it
3443 // handles the message.
3444 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003445 looper->sendMessage(this, Message(MSG_EXIT));
3446 }
3447};
3448
3449
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003450status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3451 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003452 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003453 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003454 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003455
3456 if (CC_UNLIKELY(display == 0))
3457 return BAD_VALUE;
3458
3459 if (CC_UNLIKELY(producer == 0))
3460 return BAD_VALUE;
3461
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003462 // if we have secure windows on this display, never allow the screen capture
3463 // unless the producer interface is local (i.e.: we can take a screenshot for
3464 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003465 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003466
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003467 // Convert to surfaceflinger's internal rotation type.
3468 Transform::orientation_flags rotationFlags;
3469 switch (rotation) {
3470 case ISurfaceComposer::eRotateNone:
3471 rotationFlags = Transform::ROT_0;
3472 break;
3473 case ISurfaceComposer::eRotate90:
3474 rotationFlags = Transform::ROT_90;
3475 break;
3476 case ISurfaceComposer::eRotate180:
3477 rotationFlags = Transform::ROT_180;
3478 break;
3479 case ISurfaceComposer::eRotate270:
3480 rotationFlags = Transform::ROT_270;
3481 break;
3482 default:
3483 rotationFlags = Transform::ROT_0;
3484 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3485 break;
3486 }
3487
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003488 class MessageCaptureScreen : public MessageBase {
3489 SurfaceFlinger* flinger;
3490 sp<IBinder> display;
3491 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003492 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003493 uint32_t reqWidth, reqHeight;
3494 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003495 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003496 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003497 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003498 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003499 public:
3500 MessageCaptureScreen(SurfaceFlinger* flinger,
3501 const sp<IBinder>& display,
3502 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003503 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003504 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003505 bool useIdentityTransform,
3506 Transform::orientation_flags rotation,
3507 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003508 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003509 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003510 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003511 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003512 rotation(rotation), result(PERMISSION_DENIED),
3513 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003514 {
3515 }
3516 status_t getResult() const {
3517 return result;
3518 }
3519 virtual bool handler() {
3520 Mutex::Autolock _l(flinger->mStateLock);
3521 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003522 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003523 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003524 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003525 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003526 return true;
3527 }
3528 };
3529
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003530 // this creates a "fake" BBinder which will serve as a "fake" remote
3531 // binder to receive the marshaled calls and forward them to the
3532 // real remote (a BpGraphicBufferProducer)
3533 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3534
3535 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3536 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003537 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003538 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003539 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003540 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003541
3542 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003543 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003544 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003545 }
3546 return res;
3547}
3548
Mathias Agopian180f10d2013-04-10 22:55:41 -07003549
3550void SurfaceFlinger::renderScreenImplLocked(
3551 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003552 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003553 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003554 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003555{
3556 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003557 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003558
3559 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003560 const int32_t hw_w = hw->getWidth();
3561 const int32_t hw_h = hw->getHeight();
3562 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003563 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003564
Dan Stozac1879002014-05-22 15:59:05 -07003565 // if a default or invalid sourceCrop is passed in, set reasonable values
3566 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3567 !sourceCrop.isValid()) {
3568 sourceCrop.setLeftTop(Point(0, 0));
3569 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3570 }
3571
3572 // ensure that sourceCrop is inside screen
3573 if (sourceCrop.left < 0) {
3574 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3575 }
Dan Stozabe31f442014-06-11 11:20:54 -07003576 if (sourceCrop.right > hw_w) {
3577 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003578 }
3579 if (sourceCrop.top < 0) {
3580 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3581 }
Dan Stozabe31f442014-06-11 11:20:54 -07003582 if (sourceCrop.bottom > hw_h) {
3583 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003584 }
3585
Mathias Agopian180f10d2013-04-10 22:55:41 -07003586 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003587 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003588
3589 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003590 engine.setViewportAndProjection(
3591 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003592 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003593
3594 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003595 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003596
3597 const LayerVector& layers( mDrawingState.layersSortedByZ );
3598 const size_t count = layers.size();
3599 for (size_t i=0 ; i<count ; ++i) {
3600 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003601 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003602 if (state.layerStack == hw->getLayerStack()) {
3603 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3604 if (layer->isVisible()) {
3605 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003606 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003607 if (filtering) layer->setFiltering(false);
3608 }
3609 }
3610 }
3611 }
3612
Mathias Agopian931bda12013-08-28 18:11:46 -07003613 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003614}
3615
3616
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003617status_t SurfaceFlinger::captureScreenImplLocked(
3618 const sp<const DisplayDevice>& hw,
3619 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003620 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003621 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003622 bool useIdentityTransform, Transform::orientation_flags rotation,
3623 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003624{
3625 ATRACE_CALL();
3626
Mathias Agopian180f10d2013-04-10 22:55:41 -07003627 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003628 uint32_t hw_w = hw->getWidth();
3629 uint32_t hw_h = hw->getHeight();
3630
3631 if (rotation & Transform::ROT_90) {
3632 std::swap(hw_w, hw_h);
3633 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003634
Mathias Agopian180f10d2013-04-10 22:55:41 -07003635 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3636 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3637 reqWidth, reqHeight, hw_w, hw_h);
3638 return BAD_VALUE;
3639 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003640
Mathias Agopian180f10d2013-04-10 22:55:41 -07003641 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3642 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3643
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003644 bool secureLayerIsVisible = false;
3645 const LayerVector& layers(mDrawingState.layersSortedByZ);
3646 const size_t count = layers.size();
3647 for (size_t i = 0 ; i < count ; ++i) {
3648 const sp<Layer>& layer(layers[i]);
3649 const Layer::State& state(layer->getDrawingState());
3650 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3651 state.z <= maxLayerZ && layer->isVisible() &&
3652 layer->isSecure()) {
3653 secureLayerIsVisible = true;
3654 }
3655 }
3656
3657 if (!isLocalScreenshot && secureLayerIsVisible) {
3658 ALOGW("FB is protected: PERMISSION_DENIED");
3659 return PERMISSION_DENIED;
3660 }
3661
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003662 // create a surface (because we're a producer, and we need to
3663 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003664 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003665
3666 // Put the screenshot Surface into async mode so that
3667 // Layer::headFenceHasSignaled will always return true and we'll latch the
3668 // first buffer regardless of whether or not its acquire fence has
3669 // signaled. This is needed to avoid a race condition in the rotation
3670 // animation. See b/30209608
3671 sur->setAsyncMode(true);
3672
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003673 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003674
Michael Lentine5a16a622015-05-21 13:48:24 -07003675 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3676 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003677 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3678 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003679
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003680 int err = 0;
3681 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003682 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003683 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3684 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003685
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003686 if (err == NO_ERROR) {
3687 ANativeWindowBuffer* buffer;
3688 /* TODO: Once we have the sync framework everywhere this can use
3689 * server-side waits on the fence that dequeueBuffer returns.
3690 */
3691 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3692 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003693 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003694 // create an EGLImage from the buffer so we can later
3695 // turn it into a texture
3696 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3697 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3698 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003699 // this binds the given EGLImage as a framebuffer for the
3700 // duration of this scope.
3701 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3702 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003703 // this will in fact render into our dequeued buffer
3704 // via an FBO, which means we didn't have to create
3705 // an EGLSurface and therefore we're not
3706 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003707 renderScreenImplLocked(
3708 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3709 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003710
Riley Andrews86639902014-08-15 12:27:24 -07003711 // Attempt to create a sync khr object that can produce a sync point. If that
3712 // isn't available, create a non-dupable sync object in the fallback path and
3713 // wait on it directly.
3714 EGLSyncKHR sync;
3715 if (!DEBUG_SCREENSHOTS) {
3716 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003717 // native fence fd will not be populated until flush() is done.
3718 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003719 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003720 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003721 }
Riley Andrews86639902014-08-15 12:27:24 -07003722 if (sync != EGL_NO_SYNC_KHR) {
3723 // get the sync fd
3724 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3725 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3726 ALOGW("captureScreen: failed to dup sync khr object");
3727 syncFd = -1;
3728 }
3729 eglDestroySyncKHR(mEGLDisplay, sync);
3730 } else {
3731 // fallback path
3732 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3733 if (sync != EGL_NO_SYNC_KHR) {
3734 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3735 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3736 EGLint eglErr = eglGetError();
3737 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3738 ALOGW("captureScreen: fence wait timed out");
3739 } else {
3740 ALOGW_IF(eglErr != EGL_SUCCESS,
3741 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3742 }
3743 eglDestroySyncKHR(mEGLDisplay, sync);
3744 } else {
3745 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3746 }
3747 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003748 if (DEBUG_SCREENSHOTS) {
3749 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3750 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3751 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3752 hw, minLayerZ, maxLayerZ);
3753 delete [] pixels;
3754 }
3755
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003756 } else {
3757 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3758 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003759 window->cancelBuffer(window, buffer, syncFd);
3760 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003761 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003762 // destroy our image
3763 eglDestroyImageKHR(mEGLDisplay, image);
3764 } else {
3765 result = BAD_VALUE;
3766 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003767 if (buffer) {
3768 // queueBuffer takes ownership of syncFd
3769 result = window->queueBuffer(window, buffer, syncFd);
3770 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003771 }
3772 } else {
3773 result = BAD_VALUE;
3774 }
3775 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3776 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003777
Mathias Agopian74c40c02010-09-29 13:02:36 -07003778 return result;
3779}
3780
Mathias Agopiand5556842013-09-19 17:08:37 -07003781void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3782 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003783 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003784 for (size_t y=0 ; y<h ; y++) {
3785 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3786 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003787 if (p[x] != 0xFF000000) return;
3788 }
3789 }
3790 ALOGE("*** we just took a black screenshot ***\n"
3791 "requested minz=%d, maxz=%d, layerStack=%d",
3792 minLayerZ, maxLayerZ, hw->getLayerStack());
3793 const LayerVector& layers( mDrawingState.layersSortedByZ );
3794 const size_t count = layers.size();
3795 for (size_t i=0 ; i<count ; ++i) {
3796 const sp<Layer>& layer(layers[i]);
3797 const Layer::State& state(layer->getDrawingState());
3798 const bool visible = (state.layerStack == hw->getLayerStack())
3799 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3800 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003801 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003802 visible ? '+' : '-',
3803 i, layer->getName().string(), state.layerStack, state.z,
3804 layer->isVisible(), state.flags, state.alpha);
3805 }
3806 }
3807}
3808
Pablo Ceballosce796e72016-02-04 19:10:51 -08003809bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3810 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3811 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3812}
3813
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003814// ---------------------------------------------------------------------------
3815
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003816SurfaceFlinger::LayerVector::LayerVector() {
3817}
3818
3819SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003820 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003821}
3822
3823int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3824 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003825{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003826 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003827 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3828 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003829
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003830 uint32_t ls = l->getCurrentState().layerStack;
3831 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003832 if (ls != rs)
3833 return ls - rs;
3834
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003835 uint32_t lz = l->getCurrentState().z;
3836 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003837 if (lz != rz)
3838 return lz - rz;
3839
3840 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003841}
3842
3843// ---------------------------------------------------------------------------
3844
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003845SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003846 : type(DisplayDevice::DISPLAY_ID_INVALID),
3847 layerStack(DisplayDevice::NO_LAYER_STACK),
3848 orientation(0),
3849 width(0),
3850 height(0),
3851 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003852}
3853
Pablo Ceballos53390e12015-08-04 11:25:59 -07003854SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3855 DisplayDevice::DisplayType type, bool isSecure)
3856 : type(type),
3857 layerStack(DisplayDevice::NO_LAYER_STACK),
3858 orientation(0),
3859 width(0),
3860 height(0),
3861 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003862 viewport.makeInvalid();
3863 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003864}
3865
3866// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003868}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003869
3870
3871#if defined(__gl_h_)
3872#error "don't include gl/gl.h in this file"
3873#endif
3874
3875#if defined(__gl2_h_)
3876#error "don't include gl2/gl2.h in this file"
3877#endif