blob: 9e6b0e4132e009be17f065471fc396093a2cb008 [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");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800195}
196
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800197void SurfaceFlinger::onFirstRef()
198{
199 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800200}
201
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800202SurfaceFlinger::~SurfaceFlinger()
203{
Mathias Agopiana4912602012-07-12 14:25:33 -0700204 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
205 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
206 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800207}
208
Dan Stozac7014012014-02-14 15:03:43 -0800209void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800210{
211 // the window manager died on us. prepare its eulogy.
212
Andy McFadden13a082e2012-08-24 10:16:42 -0700213 // restore initial conditions (default device unblank, etc)
214 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800215
216 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700217 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800218}
219
Mathias Agopian7e27f052010-05-28 14:22:23 -0700220sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800221{
Mathias Agopian96f08192010-06-02 23:28:45 -0700222 sp<ISurfaceComposerClient> bclient;
223 sp<Client> client(new Client(this));
224 status_t err = client->initCheck();
225 if (err == NO_ERROR) {
226 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800228 return bclient;
229}
230
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700231sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
232 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700233{
234 class DisplayToken : public BBinder {
235 sp<SurfaceFlinger> flinger;
236 virtual ~DisplayToken() {
237 // no more references, this display must be terminated
238 Mutex::Autolock _l(flinger->mStateLock);
239 flinger->mCurrentState.displays.removeItem(this);
240 flinger->setTransactionFlags(eDisplayTransactionNeeded);
241 }
242 public:
243 DisplayToken(const sp<SurfaceFlinger>& flinger)
244 : flinger(flinger) {
245 }
246 };
247
248 sp<BBinder> token = new DisplayToken(this);
249
250 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700251 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700252 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700253 mCurrentState.displays.add(token, info);
254
255 return token;
256}
257
Jesse Hall6c913be2013-08-08 12:15:49 -0700258void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
259 Mutex::Autolock _l(mStateLock);
260
261 ssize_t idx = mCurrentState.displays.indexOfKey(display);
262 if (idx < 0) {
263 ALOGW("destroyDisplay: invalid display token");
264 return;
265 }
266
267 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
268 if (!info.isVirtualDisplay()) {
269 ALOGE("destroyDisplay called for non-virtual display");
270 return;
271 }
272
273 mCurrentState.displays.removeItemsAt(idx);
274 setTransactionFlags(eDisplayTransactionNeeded);
275}
276
Jesse Hall692c7232012-11-08 15:41:56 -0800277void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800278 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800279 ALOGW_IF(mBuiltinDisplays[type],
280 "Overwriting display token for display type %d", type);
281 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800282 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700283 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800284 mCurrentState.displays.add(mBuiltinDisplays[type], info);
285}
286
Mathias Agopiane57f2922012-08-09 16:29:12 -0700287sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700288 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700289 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
290 return NULL;
291 }
Jesse Hall692c7232012-11-08 15:41:56 -0800292 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700293}
294
Jamie Gennis9a78c902011-01-12 18:30:40 -0800295sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
296{
297 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
298 return gba;
299}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700300
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800301void SurfaceFlinger::bootFinished()
302{
303 const nsecs_t now = systemTime();
304 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000305 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700306 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700307
308 // wait patiently for the window manager death
309 const String16 name("window");
310 sp<IBinder> window(defaultServiceManager()->getService(name));
311 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700312 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700313 }
314
315 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700316 // formerly we would just kill the process, but we now ask it to exit so it
317 // can choose where to stop the animation.
318 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700319
320 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
321 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
322 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800323}
324
Mathias Agopian3f844832013-08-07 21:24:32 -0700325void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700326 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700327 RenderEngine& engine;
328 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700329 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700330 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
331 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700332 }
333 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700334 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700335 return true;
336 }
337 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700338 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700339}
340
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700341class DispSyncSource : public VSyncSource, private DispSync::Callback {
342public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700343 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000344 const char* name) :
345 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700346 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700347 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000348 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
349 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700350 mDispSync(dispSync),
351 mCallbackMutex(),
352 mCallback(),
353 mVsyncMutex(),
354 mPhaseOffset(phaseOffset),
355 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700356
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700357 virtual ~DispSyncSource() {}
358
359 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700360 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700361 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000362 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700363 static_cast<DispSync::Callback*>(this));
364 if (err != NO_ERROR) {
365 ALOGE("error registering vsync callback: %s (%d)",
366 strerror(-err), err);
367 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700368 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700369 } else {
370 status_t err = mDispSync->removeEventListener(
371 static_cast<DispSync::Callback*>(this));
372 if (err != NO_ERROR) {
373 ALOGE("error unregistering vsync callback: %s (%d)",
374 strerror(-err), err);
375 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700376 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700377 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700378 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700379 }
380
381 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700382 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700383 mCallback = callback;
384 }
385
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700386 virtual void setPhaseOffset(nsecs_t phaseOffset) {
387 Mutex::Autolock lock(mVsyncMutex);
388
389 // Normalize phaseOffset to [0, period)
390 auto period = mDispSync->getPeriod();
391 phaseOffset %= period;
392 if (phaseOffset < 0) {
393 // If we're here, then phaseOffset is in (-period, 0). After this
394 // operation, it will be in (0, period)
395 phaseOffset += period;
396 }
397 mPhaseOffset = phaseOffset;
398
399 // If we're not enabled, we don't need to mess with the listeners
400 if (!mEnabled) {
401 return;
402 }
403
404 // Remove the listener with the old offset
405 status_t err = mDispSync->removeEventListener(
406 static_cast<DispSync::Callback*>(this));
407 if (err != NO_ERROR) {
408 ALOGE("error unregistering vsync callback: %s (%d)",
409 strerror(-err), err);
410 }
411
412 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000413 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700414 static_cast<DispSync::Callback*>(this));
415 if (err != NO_ERROR) {
416 ALOGE("error registering vsync callback: %s (%d)",
417 strerror(-err), err);
418 }
419 }
420
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700421private:
422 virtual void onDispSyncEvent(nsecs_t when) {
423 sp<VSyncSource::Callback> callback;
424 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700425 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700426 callback = mCallback;
427
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700428 if (mTraceVsync) {
429 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700430 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700431 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 }
433
434 if (callback != NULL) {
435 callback->onVSyncEvent(when);
436 }
437 }
438
Tim Murray4a4e4a22016-04-19 16:29:23 +0000439 const char* const mName;
440
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700441 int mValue;
442
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700443 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700444 const String8 mVsyncOnLabel;
445 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700446
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700448
449 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700450 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700451
452 Mutex mVsyncMutex; // Protects the following
453 nsecs_t mPhaseOffset;
454 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700455};
456
457void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700458 ALOGI( "SurfaceFlinger's main thread ready to run. "
459 "Initializing graphics H/W...");
460
Dan Stoza9e56aa02015-11-02 13:00:03 -0800461 { // Autolock scope
462 Mutex::Autolock _l(mStateLock);
463
464 // initialize EGL for the default display
465 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
466 eglInitialize(mEGLDisplay, NULL, NULL);
467
468 // start the EventThread
469 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
470 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000471 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800472 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
473 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000474 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800475 mEventQueue.setEventThread(mSFEventThread);
476
Tim Murray41a38532016-06-22 12:42:10 -0700477 // set EventThread and SFEventThread to SCHED_FIFO for minimum jitter
478 struct sched_param param = {0};
479 param.sched_priority = 1;
480 if (sched_setscheduler(mEventThread->getTid(), SCHED_FIFO, &param) != 0) {
481 ALOGE("Couldn't set SCHED_FIFO for EventThread");
482 }
483
484 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
485 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
486 }
487
488
Dan Stoza9e56aa02015-11-02 13:00:03 -0800489 // Get a RenderEngine for the given display / config (can't fail)
490 mRenderEngine = RenderEngine::create(mEGLDisplay,
491 HAL_PIXEL_FORMAT_RGBA_8888);
492 }
493
494 // Drop the state lock while we initialize the hardware composer. We drop
495 // the lock because on creation, it will call back into SurfaceFlinger to
496 // initialize the primary display.
497 mHwc = new HWComposer(this);
498 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
499
Jesse Hall692c7232012-11-08 15:41:56 -0800500 Mutex::Autolock _l(mStateLock);
501
Mathias Agopian875d8e12013-06-07 15:35:48 -0700502 // retrieve the EGL context that was selected/created
503 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700504
Mathias Agopianda27af92012-09-13 18:17:13 -0700505 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
506 "couldn't create EGLContext");
507
Dan Stoza9e56aa02015-11-02 13:00:03 -0800508 // make the GLContext current so that we can create textures when creating
509 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700510 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
511
Jamie Gennisd1700752013-10-14 12:22:52 -0700512 mEventControlThread = new EventControlThread(this);
513 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
514
Mathias Agopian92a979a2012-08-02 18:32:23 -0700515 // initialize our drawing state
516 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700517
Andy McFadden13a082e2012-08-24 10:16:42 -0700518 // set initial conditions (e.g. unblank default device)
519 initializeDisplays();
520
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700521 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700522 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800523
Dan Stoza9e56aa02015-11-02 13:00:03 -0800524 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700525}
526
Mathias Agopiana67e4182012-06-19 17:26:12 -0700527void SurfaceFlinger::startBootAnim() {
528 // start boot animation
529 property_set("service.bootanim.exit", "0");
530 property_set("ctl.start", "bootanim");
531}
532
Mathias Agopian875d8e12013-06-07 15:35:48 -0700533size_t SurfaceFlinger::getMaxTextureSize() const {
534 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700535}
536
Mathias Agopian875d8e12013-06-07 15:35:48 -0700537size_t SurfaceFlinger::getMaxViewportDims() const {
538 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700539}
540
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800542
Jamie Gennis582270d2011-08-17 18:19:00 -0700543bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800544 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800545 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800546 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700547 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800548}
549
Dan Stoza7f7da322014-05-02 15:26:25 -0700550status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
551 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700552 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700553 return BAD_VALUE;
554 }
555
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500556 if (!display.get())
557 return NAME_NOT_FOUND;
558
Jesse Hall692c7232012-11-08 15:41:56 -0800559 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700560 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800561 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700562 type = i;
563 break;
564 }
565 }
566
567 if (type < 0) {
568 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700569 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700570
Mathias Agopian8b736f12012-08-13 17:54:26 -0700571 // TODO: Not sure if display density should handled by SF any longer
572 class Density {
573 static int getDensityFromProperty(char const* propName) {
574 char property[PROPERTY_VALUE_MAX];
575 int density = 0;
576 if (property_get(propName, property, NULL) > 0) {
577 density = atoi(property);
578 }
579 return density;
580 }
581 public:
582 static int getEmuDensity() {
583 return getDensityFromProperty("qemu.sf.lcd_density"); }
584 static int getBuildDensity() {
585 return getDensityFromProperty("ro.sf.lcd_density"); }
586 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700587
Dan Stoza7f7da322014-05-02 15:26:25 -0700588 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700589
Dan Stoza9e56aa02015-11-02 13:00:03 -0800590 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700591 DisplayInfo info = DisplayInfo();
592
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593 float xdpi = hwConfig->getDpiX();
594 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700595
596 if (type == DisplayDevice::DISPLAY_PRIMARY) {
597 // The density of the device is provided by a build property
598 float density = Density::getBuildDensity() / 160.0f;
599 if (density == 0) {
600 // the build doesn't provide a density -- this is wrong!
601 // use xdpi instead
602 ALOGE("ro.sf.lcd_density must be defined as a build property");
603 density = xdpi / 160.0f;
604 }
605 if (Density::getEmuDensity()) {
606 // if "qemu.sf.lcd_density" is specified, it overrides everything
607 xdpi = ydpi = density = Density::getEmuDensity();
608 density /= 160.0f;
609 }
610 info.density = density;
611
612 // TODO: this needs to go away (currently needed only by webkit)
613 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
614 info.orientation = hw->getOrientation();
615 } else {
616 // TODO: where should this value come from?
617 static const int TV_DENSITY = 213;
618 info.density = TV_DENSITY / 160.0f;
619 info.orientation = 0;
620 }
621
Dan Stoza9e56aa02015-11-02 13:00:03 -0800622 info.w = hwConfig->getWidth();
623 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700624 info.xdpi = xdpi;
625 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800626 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700627 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800628
Andy McFadden91b2ca82014-06-13 14:04:23 -0700629 // This is how far in advance a buffer must be queued for
630 // presentation at a given time. If you want a buffer to appear
631 // on the screen at time N, you must submit the buffer before
632 // (N - presentationDeadline).
633 //
634 // Normally it's one full refresh period (to give SF a chance to
635 // latch the buffer), but this can be reduced by configuring a
636 // DispSync offset. Any additional delays introduced by the hardware
637 // composer or panel must be accounted for here.
638 //
639 // We add an additional 1ms to allow for processing time and
640 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800641 info.presentationDeadline = hwConfig->getVsyncPeriod() -
642 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700643
644 // All non-virtual displays are currently considered secure.
645 info.secure = true;
646
Courtney Goeltzenleuchterfad9d8c2016-06-23 11:49:50 -0600647 // DisplayManager expects each color mode to be its own display
648 // info record.
649 std::vector<int32_t> modes = getHwComposer().getColorModes(type);
650
651 if (modes.size() == 0) {
652 info.colorTransform = 0;
653 configs->push_back(info);
654 }
655 for (int32_t mode : modes) {
656 info.colorTransform = mode;
657 configs->push_back(info);
658 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700659 }
660
Dan Stoza7f7da322014-05-02 15:26:25 -0700661 return NO_ERROR;
662}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700663
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800664status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700665 DisplayStatInfo* stats) {
666 if (stats == NULL) {
667 return BAD_VALUE;
668 }
669
670 // FIXME for now we always return stats for the primary display
671 memset(stats, 0, sizeof(*stats));
672 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
673 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
674 return NO_ERROR;
675}
676
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700677int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700678 sp<DisplayDevice> device(getDisplayDevice(display));
679 if (device != NULL) {
680 return device->getActiveConfig();
681 }
682 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700683}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700684
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700685void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
686 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
687 this);
688 int32_t type = hw->getDisplayType();
689 int currentMode = hw->getActiveConfig();
690
691 if (mode == currentMode) {
692 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
693 return;
694 }
695
696 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
697 ALOGW("Trying to set config for virtual display");
698 return;
699 }
700
701 hw->setActiveConfig(mode);
702 getHwComposer().setActiveConfig(type, mode);
703}
704
705status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
706 class MessageSetActiveConfig: public MessageBase {
707 SurfaceFlinger& mFlinger;
708 sp<IBinder> mDisplay;
709 int mMode;
710 public:
711 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
712 int mode) :
713 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
714 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700715 Vector<DisplayInfo> configs;
716 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700717 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700718 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700719 mMode, configs.size());
720 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700721 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
722 if (hw == NULL) {
723 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700724 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700725 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
726 ALOGW("Attempt to set active config = %d for virtual display",
727 mMode);
728 } else {
729 mFlinger.setActiveConfigInternal(hw, mMode);
730 }
731 return true;
732 }
733 };
734 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
735 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700736 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700737}
738
Svetoslavd85084b2014-03-20 10:28:31 -0700739status_t SurfaceFlinger::clearAnimationFrameStats() {
740 Mutex::Autolock _l(mStateLock);
741 mAnimFrameTracker.clearStats();
742 return NO_ERROR;
743}
744
745status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
746 Mutex::Autolock _l(mStateLock);
747 mAnimFrameTracker.getStats(outStats);
748 return NO_ERROR;
749}
750
Dan Stozac4f471e2016-03-24 09:31:08 -0700751status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
752 HdrCapabilities* outCapabilities) const {
753 Mutex::Autolock _l(mStateLock);
754
755 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
756 if (displayDevice == nullptr) {
757 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
758 return BAD_VALUE;
759 }
760
761 std::unique_ptr<HdrCapabilities> capabilities =
762 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
763 if (capabilities) {
764 std::swap(*outCapabilities, *capabilities);
765 } else {
766 return BAD_VALUE;
767 }
768
769 return NO_ERROR;
770}
771
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800772// ----------------------------------------------------------------------------
773
774sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800775 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700776}
777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800778// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800779
780void SurfaceFlinger::waitForEvent() {
781 mEventQueue.waitMessage();
782}
783
784void SurfaceFlinger::signalTransaction() {
785 mEventQueue.invalidate();
786}
787
788void SurfaceFlinger::signalLayerUpdate() {
789 mEventQueue.invalidate();
790}
791
792void SurfaceFlinger::signalRefresh() {
793 mEventQueue.refresh();
794}
795
796status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800797 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800798 return mEventQueue.postMessage(msg, reltime);
799}
800
801status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800802 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800803 status_t res = mEventQueue.postMessage(msg, reltime);
804 if (res == NO_ERROR) {
805 msg->wait();
806 }
807 return res;
808}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800809
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700810void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700811 do {
812 waitForEvent();
813 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800814}
815
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700816void SurfaceFlinger::enableHardwareVsync() {
817 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700818 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700819 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700820 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
821 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700822 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700823 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700824}
825
Jesse Hall948fe0c2013-10-14 12:56:09 -0700826void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700827 Mutex::Autolock _l(mHWVsyncLock);
828
Jesse Hall948fe0c2013-10-14 12:56:09 -0700829 if (makeAvailable) {
830 mHWVsyncAvailable = true;
831 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700832 // Hardware vsync is not currently available, so abort the resync
833 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700834 return;
835 }
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
838 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700839
840 mPrimaryDispSync.reset();
841 mPrimaryDispSync.setPeriod(period);
842
843 if (!mPrimaryHWVsyncEnabled) {
844 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700845 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
846 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700847 mPrimaryHWVsyncEnabled = true;
848 }
849}
850
Jesse Hall948fe0c2013-10-14 12:56:09 -0700851void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700852 Mutex::Autolock _l(mHWVsyncLock);
853 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700854 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
855 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700856 mPrimaryDispSync.endResync();
857 mPrimaryHWVsyncEnabled = false;
858 }
Jesse Hall948fe0c2013-10-14 12:56:09 -0700859 if (makeUnavailable) {
860 mHWVsyncAvailable = false;
861 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700862}
863
Tim Murray4a4e4a22016-04-19 16:29:23 +0000864void SurfaceFlinger::resyncWithRateLimit() {
865 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
866 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700867 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000868 }
869}
870
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -0700872 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700873
Jamie Gennisd1700752013-10-14 12:22:52 -0700874 { // Scope for the lock
875 Mutex::Autolock _l(mHWVsyncLock);
876 if (type == 0 && mPrimaryHWVsyncEnabled) {
877 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700878 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700879 }
Jamie Gennisd1700752013-10-14 12:22:52 -0700880
881 if (needsHwVsync) {
882 enableHardwareVsync();
883 } else {
884 disableHardwareVsync(false);
885 }
Mathias Agopian148994e2012-09-19 17:31:36 -0700886}
887
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
889 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
890 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
891 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700892
Dan Stoza9e56aa02015-11-02 13:00:03 -0800893 // All non-virtual displays are currently considered secure.
894 bool isSecure = true;
895
896 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
897 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
898 wp<IBinder> token = mBuiltinDisplays[type];
899
900 sp<IGraphicBufferProducer> producer;
901 sp<IGraphicBufferConsumer> consumer;
902 BufferQueue::createBufferQueue(&producer, &consumer,
903 new GraphicBufferAlloc());
904
905 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
906 DisplayDevice::DISPLAY_PRIMARY, consumer);
907 sp<DisplayDevice> hw = new DisplayDevice(this,
908 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
909 producer, mRenderEngine->getEGLConfig());
910 mDisplays.add(token, hw);
911 } else {
912 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700913 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -0800914 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800915 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700916 } else {
Jesse Hall692c7232012-11-08 15:41:56 -0800917 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
918 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -0700919 }
920 setTransactionFlags(eDisplayTransactionNeeded);
921
Andy McFadden9e9689c2012-10-10 18:17:51 -0700922 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700923 }
Mathias Agopian86303202012-07-24 22:46:10 -0700924}
925
Dan Stoza9e56aa02015-11-02 13:00:03 -0800926void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700927 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800928 getHwComposer().setVsyncEnabled(disp,
929 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -0700930}
931
Mathias Agopian4fec8732012-06-29 14:12:52 -0700932void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -0800933 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800934 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -0800935 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -0700936 bool frameMissed = !mHadClientComposition &&
937 mPreviousPresentFence != Fence::NO_FENCE &&
938 mPreviousPresentFence->getSignalTime() == INT64_MAX;
939 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
940 if (frameMissed) {
941 signalLayerUpdate();
942 break;
943 }
944
Dan Stoza6b9454d2014-11-07 16:00:59 -0800945 bool refreshNeeded = handleMessageTransaction();
946 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -0800947 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -0800948 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -0800949 // Signal a refresh if a transaction modified the window state,
950 // a new buffer was latched, or if HWC has requested a full
951 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -0800952 signalRefresh();
953 }
954 break;
955 }
956 case MessageQueue::REFRESH: {
957 handleMessageRefresh();
958 break;
959 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800960 }
961}
962
Dan Stoza6b9454d2014-11-07 16:00:59 -0800963bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700964 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -0700965 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -0700966 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -0800967 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700968 }
Dan Stoza6b9454d2014-11-07 16:00:59 -0800969 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -0700970}
971
Dan Stoza6b9454d2014-11-07 16:00:59 -0800972bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700973 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -0800974 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -0700975}
976
977void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -0700978 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -0700979
Pablo Ceballos40845df2016-01-25 17:41:15 -0800980 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700981
Dan Stoza05dacfb2016-07-01 13:33:38 -0700982 preComposition();
983 rebuildLayerStacks();
984 setUpHWComposer();
985 doDebugFlashRegions();
986 doComposition();
987 postComposition(refreshStartTime);
988
989 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
990 mHadClientComposition = mHwc->hasClientComposition(HWC_DISPLAY_PRIMARY);
Dan Stoza14cd37c2015-07-09 12:43:33 -0700991
Dan Stoza9e56aa02015-11-02 13:00:03 -0800992 // Release any buffers which were replaced this frame
993 for (auto& layer : mLayersWithQueuedFrames) {
994 layer->releasePendingBuffer();
995 }
996 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -0700997}
Mathias Agopian4fec8732012-06-29 14:12:52 -0700998
Mathias Agopiancd60f992012-08-16 16:28:27 -0700999void SurfaceFlinger::doDebugFlashRegions()
1000{
1001 // is debugging enabled
1002 if (CC_LIKELY(!mDebugRegion))
1003 return;
1004
1005 const bool repaintEverything = mRepaintEverything;
1006 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1007 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001008 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001009 // transform the dirty region into this screen's coordinate space
1010 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1011 if (!dirtyRegion.isEmpty()) {
1012 // redraw the whole screen
1013 doComposeSurfaces(hw, Region(hw->bounds()));
1014
1015 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001016 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001017 RenderEngine& engine(getRenderEngine());
1018 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1019
Mathias Agopianda27af92012-09-13 18:17:13 -07001020 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001021 }
1022 }
1023 }
1024
1025 postFramebuffer();
1026
1027 if (mDebugRegion > 1) {
1028 usleep(mDebugRegion * 1000);
1029 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001030
Dan Stoza9e56aa02015-11-02 13:00:03 -08001031 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001032 auto& displayDevice = mDisplays[displayId];
1033 if (!displayDevice->isDisplayOn()) {
1034 continue;
1035 }
1036
1037 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001038 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1039 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001040 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001041}
1042
1043void SurfaceFlinger::preComposition()
1044{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001045 ATRACE_CALL();
1046 ALOGV("preComposition");
1047
Mathias Agopiancd60f992012-08-16 16:28:27 -07001048 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001049 const LayerVector& layers(mDrawingState.layersSortedByZ);
1050 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001051 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001052 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001053 needExtraInvalidate = true;
1054 }
1055 }
1056 if (needExtraInvalidate) {
1057 signalLayerUpdate();
1058 }
1059}
1060
Pablo Ceballos40845df2016-01-25 17:41:15 -08001061void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001062{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001063 ATRACE_CALL();
1064 ALOGV("postComposition");
1065
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001066 const LayerVector& layers(mDrawingState.layersSortedByZ);
1067 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001068 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001069 bool frameLatched = layers[i]->onPostComposition();
1070 if (frameLatched) {
1071 recordBufferingStats(layers[i]->getName().string(),
1072 layers[i]->getOccupancyHistory(false));
1073 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001074 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001075
Dan Stoza9e56aa02015-11-02 13:00:03 -08001076 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001077
1078 if (presentFence->isValid()) {
1079 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1080 enableHardwareVsync();
1081 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001082 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001083 }
1084 }
1085
Dan Stozab90cf072015-03-05 11:05:59 -08001086 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001087 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001088 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001089 enableHardwareVsync();
1090 }
1091 }
1092
Pablo Ceballos40845df2016-01-25 17:41:15 -08001093 mFenceTracker.addFrame(refreshStartTime, presentFence,
1094 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1095
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001096 if (mAnimCompositionPending) {
1097 mAnimCompositionPending = false;
1098
Jesse Halla9a1b002013-02-27 16:39:25 -08001099 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001100 mAnimFrameTracker.setActualPresentFence(presentFence);
1101 } else {
1102 // The HWC doesn't support present fences, so use the refresh
1103 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001104 nsecs_t presentTime =
1105 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001106 mAnimFrameTracker.setActualPresentTime(presentTime);
1107 }
1108 mAnimFrameTracker.advanceFrame();
1109 }
Dan Stozab90cf072015-03-05 11:05:59 -08001110
1111 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1112 return;
1113 }
1114
1115 nsecs_t currentTime = systemTime();
1116 if (mHasPoweredOff) {
1117 mHasPoweredOff = false;
1118 } else {
1119 nsecs_t period = mPrimaryDispSync.getPeriod();
1120 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1121 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1122 if (numPeriods < NUM_BUCKETS - 1) {
1123 mFrameBuckets[numPeriods] += elapsedTime;
1124 } else {
1125 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1126 }
1127 mTotalTime += elapsedTime;
1128 }
1129 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001130}
1131
1132void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001133 ATRACE_CALL();
1134 ALOGV("rebuildLayerStacks");
1135
Mathias Agopiancd60f992012-08-16 16:28:27 -07001136 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001137 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001138 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001139 mVisibleRegionsDirty = false;
1140 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001141
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001142 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001143 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001144 Region opaqueRegion;
1145 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001146 Vector<sp<Layer>> layersSortedByZ;
1147 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1148 const Transform& tr(displayDevice->getTransform());
1149 const Rect bounds(displayDevice->getBounds());
1150 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001151 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001152 displayDevice->getLayerStack(), dirtyRegion,
1153 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001154
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001155 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001156 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001157 const sp<Layer>& layer(layers[i]);
1158 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001159 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001160 Region drawRegion(tr.transform(
1161 layer->visibleNonTransparentRegion));
1162 drawRegion.andSelf(bounds);
1163 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001164 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001165 } else {
1166 // Clear out the HWC layer if this layer was
1167 // previously visible, but no longer is
1168 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1169 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001170 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001171 }
1172 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001173 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001174 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1175 displayDevice->undefinedRegion.set(bounds);
1176 displayDevice->undefinedRegion.subtractSelf(
1177 tr.transform(opaqueRegion));
1178 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001179 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001180 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001181}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001182
Mathias Agopiancd60f992012-08-16 16:28:27 -07001183void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001184 ATRACE_CALL();
1185 ALOGV("setUpHWComposer");
1186
Jesse Hall028dc8f2013-08-20 16:35:32 -07001187 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001188 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1189 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1190 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1191
1192 // If nothing has changed (!dirty), don't recompose.
1193 // If something changed, but we don't currently have any visible layers,
1194 // and didn't when we last did a composition, then skip it this time.
1195 // The second rule does two things:
1196 // - When all layers are removed from a display, we'll emit one black
1197 // frame, then nothing more until we get new layers.
1198 // - When a display is created with a private layer stack, we won't
1199 // emit any black frames until a layer is added to the layer stack.
1200 bool mustRecompose = dirty && !(empty && wasEmpty);
1201
1202 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1203 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1204 mustRecompose ? "doing" : "skipping",
1205 dirty ? "+" : "-",
1206 empty ? "+" : "-",
1207 wasEmpty ? "+" : "-");
1208
Dan Stoza71433162014-02-04 16:22:36 -08001209 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001210
1211 if (mustRecompose) {
1212 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1213 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001214 }
1215
Dan Stoza9e56aa02015-11-02 13:00:03 -08001216 // build the h/w work list
1217 if (CC_UNLIKELY(mGeometryInvalid)) {
1218 mGeometryInvalid = false;
1219 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1220 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1221 const auto hwcId = displayDevice->getHwcDisplayId();
1222 if (hwcId >= 0) {
1223 const Vector<sp<Layer>>& currentLayers(
1224 displayDevice->getVisibleLayersSortedByZ());
1225 bool foundLayerWithoutHwc = false;
1226 for (auto& layer : currentLayers) {
1227 if (!layer->hasHwcLayer(hwcId)) {
1228 auto hwcLayer = mHwc->createLayer(hwcId);
1229 if (hwcLayer) {
1230 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1231 } else {
1232 layer->forceClientComposition(hwcId);
1233 foundLayerWithoutHwc = true;
1234 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001235 }
1236 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001237
Dan Stoza9e56aa02015-11-02 13:00:03 -08001238 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001239 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001240 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001241 }
1242 }
1243 }
1244 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001245 }
Riley Andrews03414a12014-07-01 14:22:59 -07001246
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001247
1248 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1249
Dan Stoza9e56aa02015-11-02 13:00:03 -08001250 // Set the per-frame data
1251 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1252 auto& displayDevice = mDisplays[displayId];
1253 const auto hwcId = displayDevice->getHwcDisplayId();
1254 if (hwcId < 0) {
1255 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001256 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001257 if (colorMatrix != mPreviousColorMatrix) {
1258 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1259 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1260 "display %zd: %d", displayId, result);
1261 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001262 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1263 layer->setPerFrameData(displayDevice);
1264 }
1265 }
1266
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001267 mPreviousColorMatrix = colorMatrix;
1268
Dan Stoza9e56aa02015-11-02 13:00:03 -08001269 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001270 auto& displayDevice = mDisplays[displayId];
1271 if (!displayDevice->isDisplayOn()) {
1272 continue;
1273 }
1274
1275 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001276 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1277 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001278 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001279}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001280
Mathias Agopiancd60f992012-08-16 16:28:27 -07001281void SurfaceFlinger::doComposition() {
1282 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001283 ALOGV("doComposition");
1284
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001285 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001286 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001287 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001288 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001289 // transform the dirty region into this screen's coordinate space
1290 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001291
1292 // repaint the framebuffer (if needed)
1293 doDisplayComposition(hw, dirtyRegion);
1294
Mathias Agopiancd60f992012-08-16 16:28:27 -07001295 hw->dirtyRegion.clear();
1296 hw->flip(hw->swapRegion);
1297 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001298 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001299 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001300 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001301}
1302
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001303void SurfaceFlinger::postFramebuffer()
1304{
Mathias Agopian841cde52012-03-01 15:44:37 -08001305 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001306 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001307
Mathias Agopiana44b0412011-10-16 18:46:35 -07001308 const nsecs_t now = systemTime();
1309 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001310
Dan Stoza9e56aa02015-11-02 13:00:03 -08001311 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1312 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001313 if (!displayDevice->isDisplayOn()) {
1314 continue;
1315 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001316 const auto hwcId = displayDevice->getHwcDisplayId();
1317 if (hwcId >= 0) {
1318 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001319 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001320 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001321 if (displayId == 0) {
1322 // Make the default display current because the VirtualDisplayDevice
1323 // code cannot deal with dequeueBuffer() being called outside of the
1324 // composition loop; however the code below can call glFlush() which
1325 // is allowed to (and does in some case) call dequeueBuffer().
1326 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1327 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001328 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1329 sp<Fence> releaseFence = Fence::NO_FENCE;
1330 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1331 releaseFence = displayDevice->getClientTargetAcquireFence();
1332 } else {
1333 auto hwcLayer = layer->getHwcLayer(hwcId);
1334 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001335 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001336 layer->onLayerDisplayed(releaseFence);
1337 }
1338 if (hwcId >= 0) {
1339 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001340 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001341 }
1342
Mathias Agopiana44b0412011-10-16 18:46:35 -07001343 mLastSwapBufferTime = systemTime() - now;
1344 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001345
1346 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1347 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1348 logFrameStats();
1349 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350}
1351
Mathias Agopian87baae12012-07-31 12:38:26 -07001352void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001353{
Mathias Agopian841cde52012-03-01 15:44:37 -08001354 ATRACE_CALL();
1355
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001356 // here we keep a copy of the drawing state (that is the state that's
1357 // going to be overwritten by handleTransactionLocked()) outside of
1358 // mStateLock so that the side-effects of the State assignment
1359 // don't happen with mStateLock held (which can cause deadlocks).
1360 State drawingState(mDrawingState);
1361
Mathias Agopianca4d3602011-05-19 15:38:14 -07001362 Mutex::Autolock _l(mStateLock);
1363 const nsecs_t now = systemTime();
1364 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001365
Mathias Agopianca4d3602011-05-19 15:38:14 -07001366 // Here we're guaranteed that some transaction flags are set
1367 // so we can call handleTransactionLocked() unconditionally.
1368 // We call getTransactionFlags(), which will also clear the flags,
1369 // with mStateLock held to guarantee that mCurrentState won't change
1370 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001371
Mathias Agopiane57f2922012-08-09 16:29:12 -07001372 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001373 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001374
Mathias Agopianca4d3602011-05-19 15:38:14 -07001375 mLastTransactionTime = systemTime() - now;
1376 mDebugInTransaction = 0;
1377 invalidateHwcGeometry();
1378 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001379}
1380
Mathias Agopian87baae12012-07-31 12:38:26 -07001381void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001382{
1383 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001384 const size_t count = currentLayers.size();
1385
Dan Stoza7dde5992015-05-22 09:51:44 -07001386 // Notify all layers of available frames
1387 for (size_t i = 0; i < count; ++i) {
1388 currentLayers[i]->notifyAvailableFrames();
1389 }
1390
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001391 /*
1392 * Traversal of the children
1393 * (perform the transaction for each of them if needed)
1394 */
1395
Mathias Agopian3559b072012-08-15 13:46:03 -07001396 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001397 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001398 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001399 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1400 if (!trFlags) continue;
1401
1402 const uint32_t flags = layer->doTransaction(0);
1403 if (flags & Layer::eVisibleRegion)
1404 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001405 }
1406 }
1407
1408 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001409 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001410 */
1411
Mathias Agopiane57f2922012-08-09 16:29:12 -07001412 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001413 // here we take advantage of Vector's copy-on-write semantics to
1414 // improve performance by skipping the transaction entirely when
1415 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001416 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1417 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001418 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001419 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001420 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001421 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001422
1423 // find the displays that were removed
1424 // (ie: in drawing state but not in current state)
1425 // also handle displays that changed
1426 // (ie: displays that are in both lists)
1427 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001428 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1429 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001430 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001431 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001432 // Call makeCurrent() on the primary display so we can
1433 // be sure that nothing associated with this display
1434 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001435 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001436 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001437 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1438 if (hw != NULL)
1439 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001440 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001441 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001442 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001443 } else {
1444 ALOGW("trying to remove the main display");
1445 }
1446 } else {
1447 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001448 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001449 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001450 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1451 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001452 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001453 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001454 // recreating the DisplayDevice, so we just remove it
1455 // from the drawing state, so that it get re-added
1456 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001457 sp<DisplayDevice> hw(getDisplayDevice(display));
1458 if (hw != NULL)
1459 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001460 mDisplays.removeItem(display);
1461 mDrawingState.displays.removeItemsAt(i);
1462 dc--; i--;
1463 // at this point we must loop to the next item
1464 continue;
1465 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001466
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001467 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001468 if (disp != NULL) {
1469 if (state.layerStack != draw[i].layerStack) {
1470 disp->setLayerStack(state.layerStack);
1471 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001472 if ((state.orientation != draw[i].orientation)
1473 || (state.viewport != draw[i].viewport)
1474 || (state.frame != draw[i].frame))
1475 {
1476 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001477 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001478 }
Michael Lentine47e45402014-07-18 15:34:25 -07001479 if (state.width != draw[i].width || state.height != draw[i].height) {
1480 disp->setDisplaySize(state.width, state.height);
1481 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001482 }
1483 }
1484 }
1485
1486 // find displays that were added
1487 // (ie: in current state but not in drawing state)
1488 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001489 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001490 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001491
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001492 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001493 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001494 sp<IGraphicBufferProducer> bqProducer;
1495 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001496 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1497 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001498
Dan Stoza9e56aa02015-11-02 13:00:03 -08001499 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001500 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001501 // Virtual displays without a surface are dormant:
1502 // they have external state (layer stack, projection,
1503 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001504 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001505
Dan Stoza1f3efb12014-10-15 16:34:55 -07001506 int width = 0;
1507 int status = state.surface->query(
1508 NATIVE_WINDOW_WIDTH, &width);
1509 ALOGE_IF(status != NO_ERROR,
1510 "Unable to query width (%d)", status);
1511 int height = 0;
1512 status = state.surface->query(
1513 NATIVE_WINDOW_HEIGHT, &height);
1514 ALOGE_IF(status != NO_ERROR,
1515 "Unable to query height (%d)", status);
Dan Stoza5cf424b2016-05-20 14:02:39 -07001516 int intFormat = 0;
1517 status = state.surface->query(
1518 NATIVE_WINDOW_FORMAT, &intFormat);
1519 ALOGE_IF(status != NO_ERROR,
1520 "Unable to query format (%d)", status);
1521 auto format = static_cast<android_pixel_format_t>(
1522 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001523
Dan Stoza5cf424b2016-05-20 14:02:39 -07001524 mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001525 &hwcId);
1526
Dan Stoza5cf424b2016-05-20 14:02:39 -07001527 // TODO: Plumb requested format back up to consumer
1528
Dan Stoza9e56aa02015-11-02 13:00:03 -08001529 sp<VirtualDisplaySurface> vds =
1530 new VirtualDisplaySurface(*mHwc,
1531 hwcId, state.surface, bqProducer,
1532 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001533
1534 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001535 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001536 }
1537 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001538 ALOGE_IF(state.surface!=NULL,
1539 "adding a supported display, but rendering "
1540 "surface is provided (%p), ignoring it",
1541 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001542 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1543 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1544 dispSurface = new FramebufferSurface(*mHwc,
1545 DisplayDevice::DISPLAY_EXTERNAL,
1546 bqConsumer);
1547 producer = bqProducer;
1548 } else {
1549 ALOGE("Attempted to add non-external non-virtual"
1550 " display");
1551 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001552 }
1553
1554 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001555 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001556 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001557 state.type, hwcId, state.isSecure, display,
1558 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001559 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001560 hw->setLayerStack(state.layerStack);
1561 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001562 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001563 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001564 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001565 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001566 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001567 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001568 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001569 }
1570 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001571 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001572 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001573
Mathias Agopian84300952012-11-21 16:02:13 -08001574 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1575 // The transform hint might have changed for some layers
1576 // (either because a display has changed, or because a layer
1577 // as changed).
1578 //
1579 // Walk through all the layers in currentLayers,
1580 // and update their transform hint.
1581 //
1582 // If a layer is visible only on a single display, then that
1583 // display is used to calculate the hint, otherwise we use the
1584 // default display.
1585 //
1586 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1587 // the hint is set before we acquire a buffer from the surface texture.
1588 //
1589 // NOTE: layer transactions have taken place already, so we use their
1590 // drawing state. However, SurfaceFlinger's own transaction has not
1591 // happened yet, so we must use the current state layer list
1592 // (soon to become the drawing state list).
1593 //
1594 sp<const DisplayDevice> disp;
1595 uint32_t currentlayerStack = 0;
1596 for (size_t i=0; i<count; i++) {
1597 // NOTE: we rely on the fact that layers are sorted by
1598 // layerStack first (so we don't have to traverse the list
1599 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001600 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001601 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001602 if (i==0 || currentlayerStack != layerStack) {
1603 currentlayerStack = layerStack;
1604 // figure out if this layerstack is mirrored
1605 // (more than one display) if so, pick the default display,
1606 // if not, pick the only display it's on.
1607 disp.clear();
1608 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1609 sp<const DisplayDevice> hw(mDisplays[dpy]);
1610 if (hw->getLayerStack() == currentlayerStack) {
1611 if (disp == NULL) {
1612 disp = hw;
1613 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001614 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001615 break;
1616 }
1617 }
1618 }
1619 }
Chet Haase91d25932013-04-11 15:24:55 -07001620 if (disp == NULL) {
1621 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1622 // redraw after transform hint changes. See bug 8508397.
1623
1624 // could be null when this layer is using a layerStack
1625 // that is not visible on any display. Also can occur at
1626 // screen off/on times.
1627 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001628 }
Chet Haase91d25932013-04-11 15:24:55 -07001629 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001630 }
1631 }
1632
1633
Mathias Agopian3559b072012-08-15 13:46:03 -07001634 /*
1635 * Perform our own transaction if needed
1636 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001637
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001638 const LayerVector& layers(mDrawingState.layersSortedByZ);
1639 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001640 // layers have been added
1641 mVisibleRegionsDirty = true;
1642 }
1643
1644 // some layers might have been removed, so
1645 // we need to update the regions they're exposing.
1646 if (mLayersRemoved) {
1647 mLayersRemoved = false;
1648 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001649 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001650 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001651 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001652 if (currentLayers.indexOf(layer) < 0) {
1653 // this layer is not visible anymore
1654 // TODO: we could traverse the tree from front to back and
1655 // compute the actual visible region
1656 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001657 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001658 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001659 Region(Rect(s.active.w, s.active.h)));
1660 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001662 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001663 }
1664
1665 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001666
1667 updateCursorAsync();
1668}
1669
1670void SurfaceFlinger::updateCursorAsync()
1671{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001672 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1673 auto& displayDevice = mDisplays[displayId];
1674 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001675 continue;
1676 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001677
1678 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1679 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001680 }
1681 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001682}
1683
1684void SurfaceFlinger::commitTransaction()
1685{
1686 if (!mLayersPendingRemoval.isEmpty()) {
1687 // Notify removed layers now that they can't be drawn from
1688 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001689 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1690 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001691 mLayersPendingRemoval[i]->onRemoved();
1692 }
1693 mLayersPendingRemoval.clear();
1694 }
1695
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001696 // If this transaction is part of a window animation then the next frame
1697 // we composite should be considered an animation as well.
1698 mAnimCompositionPending = mAnimTransactionPending;
1699
Mathias Agopian4fec8732012-06-29 14:12:52 -07001700 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001701 mTransactionPending = false;
1702 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001703 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001704}
1705
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001706void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001707 const LayerVector& currentLayers, uint32_t layerStack,
1708 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001709{
Mathias Agopian841cde52012-03-01 15:44:37 -08001710 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001711 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001713 Region aboveOpaqueLayers;
1714 Region aboveCoveredLayers;
1715 Region dirty;
1716
Mathias Agopian87baae12012-07-31 12:38:26 -07001717 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001718
1719 size_t i = currentLayers.size();
1720 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001721 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001722
1723 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001724 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001725
Jesse Hall01e29052013-02-19 16:13:35 -08001726 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001727 if (s.layerStack != layerStack)
1728 continue;
1729
Mathias Agopianab028732010-03-16 16:41:46 -07001730 /*
1731 * opaqueRegion: area of a surface that is fully opaque.
1732 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001733 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001734
1735 /*
1736 * visibleRegion: area of a surface that is visible on screen
1737 * and not fully transparent. This is essentially the layer's
1738 * footprint minus the opaque regions above it.
1739 * Areas covered by a translucent surface are considered visible.
1740 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001741 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001742
1743 /*
1744 * coveredRegion: area of a surface that is covered by all
1745 * visible regions above it (which includes the translucent areas).
1746 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001747 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001748
Jesse Halla8026d22012-09-25 13:25:04 -07001749 /*
1750 * transparentRegion: area of a surface that is hinted to be completely
1751 * transparent. This is only used to tell when the layer has no visible
1752 * non-transparent regions and can be removed from the layer list. It
1753 * does not affect the visibleRegion of this layer or any layers
1754 * beneath it. The hint may not be correct if apps don't respect the
1755 * SurfaceView restrictions (which, sadly, some don't).
1756 */
1757 Region transparentRegion;
1758
Mathias Agopianab028732010-03-16 16:41:46 -07001759
1760 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001761 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001762 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001763 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001764 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001765 if (!visibleRegion.isEmpty()) {
1766 // Remove the transparent area from the visible region
1767 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001768 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001769 if (tr.preserveRects()) {
1770 // transform the transparent region
1771 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001772 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001773 // transformation too complex, can't do the
1774 // transparent region optimization.
1775 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001776 }
Mathias Agopianab028732010-03-16 16:41:46 -07001777 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001778
Mathias Agopianab028732010-03-16 16:41:46 -07001779 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001780 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001781 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001782 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1783 // the opaque region is the layer's footprint
1784 opaqueRegion = visibleRegion;
1785 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001786 }
1787 }
1788
Mathias Agopianab028732010-03-16 16:41:46 -07001789 // Clip the covered region to the visible region
1790 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1791
1792 // Update aboveCoveredLayers for next (lower) layer
1793 aboveCoveredLayers.orSelf(visibleRegion);
1794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001795 // subtract the opaque region covered by the layers above us
1796 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001797
1798 // compute this layer's dirty region
1799 if (layer->contentDirty) {
1800 // we need to invalidate the whole region
1801 dirty = visibleRegion;
1802 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001803 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001804 layer->contentDirty = false;
1805 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001806 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001807 * the exposed region consists of two components:
1808 * 1) what's VISIBLE now and was COVERED before
1809 * 2) what's EXPOSED now less what was EXPOSED before
1810 *
1811 * note that (1) is conservative, we start with the whole
1812 * visible region but only keep what used to be covered by
1813 * something -- which mean it may have been exposed.
1814 *
1815 * (2) handles areas that were not covered by anything but got
1816 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001817 */
Mathias Agopianab028732010-03-16 16:41:46 -07001818 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001819 const Region oldVisibleRegion = layer->visibleRegion;
1820 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001821 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1822 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001823 }
1824 dirty.subtractSelf(aboveOpaqueLayers);
1825
1826 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001827 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001828
Mathias Agopianab028732010-03-16 16:41:46 -07001829 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001830 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001831
Jesse Halla8026d22012-09-25 13:25:04 -07001832 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001833 layer->setVisibleRegion(visibleRegion);
1834 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001835 layer->setVisibleNonTransparentRegion(
1836 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001837 }
1838
Mathias Agopian87baae12012-07-31 12:38:26 -07001839 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001840}
1841
Mathias Agopian87baae12012-07-31 12:38:26 -07001842void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1843 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001844 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001845 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1846 if (hw->getLayerStack() == layerStack) {
1847 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001848 }
1849 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001850}
1851
Dan Stoza6b9454d2014-11-07 16:00:59 -08001852bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001853{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001854 ALOGV("handlePageFlip");
1855
Mathias Agopian4fec8732012-06-29 14:12:52 -07001856 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001857
Mathias Agopian4fec8732012-06-29 14:12:52 -07001858 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001859 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001860 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07001861
1862 // Store the set of layers that need updates. This set must not change as
1863 // buffers are being latched, as this could result in a deadlock.
1864 // Example: Two producers share the same command stream and:
1865 // 1.) Layer 0 is latched
1866 // 2.) Layer 0 gets a new frame
1867 // 2.) Layer 1 gets a new frame
1868 // 3.) Layer 1 is latched.
1869 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1870 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07001871 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001872 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001873 if (layer->hasQueuedFrame()) {
1874 frameQueued = true;
1875 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001876 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07001877 } else {
1878 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001879 }
Dan Stozaee44edd2015-03-23 15:50:23 -07001880 } else {
1881 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001882 }
Eric Penner51c59cd2014-07-28 19:51:58 -07001883 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001884 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001885 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07001886 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001887 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07001888 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001889 }
Mathias Agopian4da75192010-08-10 17:19:56 -07001890
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001891 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001892
1893 // If we will need to wake up at some time in the future to deal with a
1894 // queued frame that shouldn't be displayed during this vsync period, wake
1895 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001896 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001897 signalLayerUpdate();
1898 }
1899
1900 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08001901 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001902}
1903
Mathias Agopianad456f92011-01-13 17:53:01 -08001904void SurfaceFlinger::invalidateHwcGeometry()
1905{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001906 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08001907}
1908
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001909
Mathias Agopiancd60f992012-08-16 16:28:27 -07001910void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07001911 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001912{
Dan Stoza71433162014-02-04 16:22:36 -08001913 // We only need to actually compose the display if:
1914 // 1) It is being handled by hardware composer, which may need this to
1915 // keep its virtual display state machine in sync, or
1916 // 2) There is work to be done (the dirty region isn't empty)
1917 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1918 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001919 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08001920 return;
1921 }
1922
Dan Stoza9e56aa02015-11-02 13:00:03 -08001923 ALOGV("doDisplayComposition");
1924
Mathias Agopian87baae12012-07-31 12:38:26 -07001925 Region dirtyRegion(inDirtyRegion);
1926
Mathias Agopianb8a55602009-06-26 19:06:36 -07001927 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07001928 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001929
Mathias Agopian42977342012-08-05 00:40:46 -07001930 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001931 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001932 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1933 // takes a rectangle, we must make sure to update that whole
1934 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07001935 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001936 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001937 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001938 // We need to redraw the rectangle that will be updated
1939 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07001940 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07001941 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07001942 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07001943 } else {
1944 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07001945 dirtyRegion.set(hw->bounds());
1946 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947 }
1948 }
1949
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001950 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001951
Mathias Agopian9c6e2972011-09-20 17:21:56 -07001952 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07001953 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07001954
1955 // swap buffers (presentation)
1956 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001957}
1958
Dan Stoza9e56aa02015-11-02 13:00:03 -08001959bool SurfaceFlinger::doComposeSurfaces(
1960 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07001961{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001962 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07001963
Dan Stoza9e56aa02015-11-02 13:00:03 -08001964 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001965
1966 mat4 oldColorMatrix;
1967 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
1968 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
1969 if (applyColorMatrix) {
1970 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1971 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
1972 }
1973
Dan Stoza9e56aa02015-11-02 13:00:03 -08001974 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
1975 if (hasClientComposition) {
1976 ALOGV("hasClientComposition");
1977
1978 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08001979 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08001980 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07001981 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1982 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1983 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1984 }
1985 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08001986 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001987
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001988 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08001989 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
1990 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07001991 // when using overlays, we assume a fully transparent framebuffer
1992 // NOTE: we could reduce how much we need to clear, for instance
1993 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07001994 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07001995 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07001997 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07001998 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002000
2001 // we remove the scissor part
2002 // we're left with the letterbox region
2003 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002004 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002005
2006 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002007 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002008
2009 // but limit it to the dirty region
2010 region.andSelf(dirty);
2011
Mathias Agopianb9494d52012-04-18 02:28:45 -07002012 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002013 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002014 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002016 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002017 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002018
Dan Stoza9e56aa02015-11-02 13:00:03 -08002019 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002020 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002021 // scissor on the main display. It should never be needed
2022 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002023 const Rect& bounds(displayDevice->getBounds());
2024 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002025 if (scissor != bounds) {
2026 // scissor doesn't match the screen's dimensions, so we
2027 // need to clear everything outside of it and enable
2028 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002029
Mathias Agopianf45c5102012-10-24 16:29:17 -07002030 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002031 const uint32_t height = displayDevice->getHeight();
2032 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002033 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002034 }
2035 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002036 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002037
Mathias Agopian85d751c2012-08-29 16:59:24 -07002038 /*
2039 * and then, render the layers targeted at the framebuffer
2040 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002041
Dan Stoza9e56aa02015-11-02 13:00:03 -08002042 ALOGV("Rendering client layers");
2043 const Transform& displayTransform = displayDevice->getTransform();
2044 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002045 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002046 bool firstLayer = true;
2047 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2048 const Region clip(dirty.intersect(
2049 displayTransform.transform(layer->visibleRegion)));
2050 ALOGV("Layer: %s", layer->getName().string());
2051 ALOGV(" Composition type: %s",
2052 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002053 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002054 switch (layer->getCompositionType(hwcId)) {
2055 case HWC2::Composition::Cursor:
2056 case HWC2::Composition::Device:
2057 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002058 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002059 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2060 layer->isOpaque(state) && (state.alpha == 1.0f)
2061 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002062 // never clear the very first layer since we're
2063 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002064 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002065 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002066 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002067 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002068 case HWC2::Composition::Client: {
2069 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002070 break;
2071 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002072 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002073 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002074 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 } else {
2076 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002077 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002078 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002079 }
2080 } else {
2081 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002082 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002083 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002084 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002085 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002086 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002087 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002088 }
2089 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002090
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002091 if (applyColorMatrix) {
2092 getRenderEngine().setupColorTransform(oldColorMatrix);
2093 }
2094
Mathias Agopianf45c5102012-10-24 16:29:17 -07002095 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002096 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002097 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002098}
2099
Mathias Agopian3f844832013-08-07 21:24:32 -07002100void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002101 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002102 RenderEngine& engine(getRenderEngine());
2103 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002104}
2105
Dan Stoza7d89d062015-04-30 13:29:25 -07002106status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002107 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002108 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002109 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002110{
Dan Stoza7d89d062015-04-30 13:29:25 -07002111 // add this layer to the current state list
2112 {
2113 Mutex::Autolock _l(mStateLock);
2114 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2115 return NO_MEMORY;
2116 }
2117 mCurrentState.layersSortedByZ.add(lbc);
2118 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2119 }
2120
Mathias Agopian96f08192010-06-02 23:28:45 -07002121 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002122 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002123
Dan Stoza7d89d062015-04-30 13:29:25 -07002124 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002125}
2126
Mathias Agopian3f844832013-08-07 21:24:32 -07002127status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002128 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002129 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002131 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002132 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002133 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002134 return NO_ERROR;
2135 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002136 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002137}
2138
Dan Stozac7014012014-02-14 15:03:43 -08002139uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002140 return android_atomic_release_load(&mTransactionFlags);
2141}
2142
Mathias Agopian3f844832013-08-07 21:24:32 -07002143uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002144 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2145}
2146
Mathias Agopian3f844832013-08-07 21:24:32 -07002147uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002148 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2149 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002150 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002151 }
2152 return old;
2153}
2154
Mathias Agopian8b33f032012-07-24 20:43:54 -07002155void SurfaceFlinger::setTransactionState(
2156 const Vector<ComposerState>& state,
2157 const Vector<DisplayState>& displays,
2158 uint32_t flags)
2159{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002160 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002161 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002162 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002163
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002164 if (flags & eAnimation) {
2165 // For window updates that are part of an animation we must wait for
2166 // previous animation "frames" to be handled.
2167 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002168 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002169 if (CC_UNLIKELY(err != NO_ERROR)) {
2170 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002171 // caller after a few seconds.
2172 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2173 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002174 mAnimTransactionPending = false;
2175 break;
2176 }
2177 }
2178 }
2179
Mathias Agopiane57f2922012-08-09 16:29:12 -07002180 size_t count = displays.size();
2181 for (size_t i=0 ; i<count ; i++) {
2182 const DisplayState& s(displays[i]);
2183 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002184 }
2185
Mathias Agopiane57f2922012-08-09 16:29:12 -07002186 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002187 for (size_t i=0 ; i<count ; i++) {
2188 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002189 // Here we need to check that the interface we're given is indeed
2190 // one of our own. A malicious client could give us a NULL
2191 // IInterface, or one of its own or even one of our own but a
2192 // different type. All these situations would cause us to crash.
2193 //
2194 // NOTE: it would be better to use RTTI as we could directly check
2195 // that we have a Client*. however, RTTI is disabled in Android.
2196 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002197 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002198 if (binder != NULL) {
2199 String16 desc(binder->getInterfaceDescriptor());
2200 if (desc == ISurfaceComposerClient::descriptor) {
2201 sp<Client> client( static_cast<Client *>(s.client.get()) );
2202 transactionFlags |= setClientStateLocked(client, s.state);
2203 }
2204 }
2205 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002206 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002207
Robert Carr2a7dbb42016-05-24 11:41:28 -07002208 // If a synchronous transaction is explicitly requested without any changes,
2209 // force a transaction anyway. This can be used as a flush mechanism for
2210 // previous async transactions.
2211 if (transactionFlags == 0 && (flags & eSynchronous)) {
2212 transactionFlags = eTransactionNeeded;
2213 }
2214
Mathias Agopian386aa982011-11-07 21:58:03 -08002215 if (transactionFlags) {
2216 // this triggers the transaction
2217 setTransactionFlags(transactionFlags);
2218
2219 // if this is a synchronous transaction, wait for it to take effect
2220 // before returning.
2221 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002222 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002223 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002224 if (flags & eAnimation) {
2225 mAnimTransactionPending = true;
2226 }
2227 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002228 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2229 if (CC_UNLIKELY(err != NO_ERROR)) {
2230 // just in case something goes wrong in SF, return to the
2231 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002232 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2233 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002234 break;
2235 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002236 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237 }
2238}
2239
Mathias Agopiane57f2922012-08-09 16:29:12 -07002240uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2241{
Jesse Hall9a143922012-10-04 16:29:19 -07002242 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2243 if (dpyIdx < 0)
2244 return 0;
2245
Mathias Agopiane57f2922012-08-09 16:29:12 -07002246 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002247 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002248 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002249 const uint32_t what = s.what;
2250 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002251 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002252 disp.surface = s.surface;
2253 flags |= eDisplayTransactionNeeded;
2254 }
2255 }
2256 if (what & DisplayState::eLayerStackChanged) {
2257 if (disp.layerStack != s.layerStack) {
2258 disp.layerStack = s.layerStack;
2259 flags |= eDisplayTransactionNeeded;
2260 }
2261 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002262 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002263 if (disp.orientation != s.orientation) {
2264 disp.orientation = s.orientation;
2265 flags |= eDisplayTransactionNeeded;
2266 }
2267 if (disp.frame != s.frame) {
2268 disp.frame = s.frame;
2269 flags |= eDisplayTransactionNeeded;
2270 }
2271 if (disp.viewport != s.viewport) {
2272 disp.viewport = s.viewport;
2273 flags |= eDisplayTransactionNeeded;
2274 }
2275 }
Michael Lentine47e45402014-07-18 15:34:25 -07002276 if (what & DisplayState::eDisplaySizeChanged) {
2277 if (disp.width != s.width) {
2278 disp.width = s.width;
2279 flags |= eDisplayTransactionNeeded;
2280 }
2281 if (disp.height != s.height) {
2282 disp.height = s.height;
2283 flags |= eDisplayTransactionNeeded;
2284 }
2285 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002286 }
2287 return flags;
2288}
2289
2290uint32_t SurfaceFlinger::setClientStateLocked(
2291 const sp<Client>& client,
2292 const layer_state_t& s)
2293{
2294 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002295 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002296 if (layer != 0) {
2297 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002298 bool geometryAppliesWithResize =
2299 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002300 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002301 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002302 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002303 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002304 }
2305 if (what & layer_state_t::eLayerChanged) {
2306 // NOTE: index needs to be calculated before we update the state
2307 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002308 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002309 mCurrentState.layersSortedByZ.removeAt(idx);
2310 mCurrentState.layersSortedByZ.add(layer);
2311 // we need traversal (state changed)
2312 // AND transaction (list changed)
2313 flags |= eTransactionNeeded|eTraversalNeeded;
2314 }
2315 }
2316 if (what & layer_state_t::eSizeChanged) {
2317 if (layer->setSize(s.w, s.h)) {
2318 flags |= eTraversalNeeded;
2319 }
2320 }
2321 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002322 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002323 flags |= eTraversalNeeded;
2324 }
2325 if (what & layer_state_t::eMatrixChanged) {
2326 if (layer->setMatrix(s.matrix))
2327 flags |= eTraversalNeeded;
2328 }
2329 if (what & layer_state_t::eTransparentRegionChanged) {
2330 if (layer->setTransparentRegionHint(s.transparentRegion))
2331 flags |= eTraversalNeeded;
2332 }
Dan Stoza23116082015-06-18 14:58:39 -07002333 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002334 if (layer->setFlags(s.flags, s.mask))
2335 flags |= eTraversalNeeded;
2336 }
2337 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002338 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002339 flags |= eTraversalNeeded;
2340 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002341 if (what & layer_state_t::eFinalCropChanged) {
2342 if (layer->setFinalCrop(s.finalCrop))
2343 flags |= eTraversalNeeded;
2344 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002345 if (what & layer_state_t::eLayerStackChanged) {
2346 // NOTE: index needs to be calculated before we update the state
2347 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002348 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002349 mCurrentState.layersSortedByZ.removeAt(idx);
2350 mCurrentState.layersSortedByZ.add(layer);
2351 // we need traversal (state changed)
2352 // AND transaction (list changed)
2353 flags |= eTransactionNeeded|eTraversalNeeded;
2354 }
2355 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002356 if (what & layer_state_t::eDeferTransaction) {
2357 layer->deferTransactionUntil(s.handle, s.frameNumber);
2358 // We don't trigger a traversal here because if no other state is
2359 // changed, we don't want this to cause any more work
2360 }
Robert Carrc3574f72016-03-24 12:19:32 -07002361 if (what & layer_state_t::eOverrideScalingModeChanged) {
2362 layer->setOverrideScalingMode(s.overrideScalingMode);
2363 // We don't trigger a traversal here because if no other state is
2364 // changed, we don't want this to cause any more work
2365 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002366 }
2367 return flags;
2368}
2369
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002370status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002371 const String8& name,
2372 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002373 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2374 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002375{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002376 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002377 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002378 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002379 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002380 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002381 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002382
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002383 status_t result = NO_ERROR;
2384
2385 sp<Layer> layer;
2386
Mathias Agopian3165cc22012-08-08 19:42:09 -07002387 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2388 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002389 result = createNormalLayer(client,
2390 name, w, h, flags, format,
2391 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002392 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002393 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002394 result = createDimLayer(client,
2395 name, w, h, flags,
2396 handle, gbp, &layer);
2397 break;
2398 default:
2399 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002400 break;
2401 }
2402
Dan Stoza7d89d062015-04-30 13:29:25 -07002403 if (result != NO_ERROR) {
2404 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002405 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002406
2407 result = addClientLayer(client, *handle, *gbp, layer);
2408 if (result != NO_ERROR) {
2409 return result;
2410 }
2411
2412 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002413 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002414}
2415
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002416status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2417 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2418 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002419{
2420 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002421 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002422 case PIXEL_FORMAT_TRANSPARENT:
2423 case PIXEL_FORMAT_TRANSLUCENT:
2424 format = PIXEL_FORMAT_RGBA_8888;
2425 break;
2426 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002427 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002428 break;
2429 }
2430
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002431 *outLayer = new Layer(this, client, name, w, h, flags);
2432 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2433 if (err == NO_ERROR) {
2434 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002435 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002436 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002437
2438 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2439 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002440}
2441
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002442status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2443 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2444 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002445{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002446 *outLayer = new LayerDim(this, client, name, w, h, flags);
2447 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002448 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002449 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002450}
2451
Mathias Agopianac9fa422013-02-11 16:40:36 -08002452status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002453{
Mathias Agopian67106042013-03-14 19:18:13 -07002454 // called by the window manager when it wants to remove a Layer
2455 status_t err = NO_ERROR;
2456 sp<Layer> l(client->getLayerUser(handle));
2457 if (l != NULL) {
2458 err = removeLayer(l);
2459 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2460 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002461 }
2462 return err;
2463}
2464
Mathias Agopian13127d82013-03-05 17:47:11 -08002465status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002466{
Mathias Agopian67106042013-03-14 19:18:13 -07002467 // called by ~LayerCleaner() when all references to the IBinder (handle)
2468 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002469 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002470 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002471 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002472 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002473 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002474 "error removing layer=%p (%s)", l.get(), strerror(-err));
2475 }
2476 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477}
2478
Mathias Agopianb60314a2012-04-10 22:09:54 -07002479// ---------------------------------------------------------------------------
2480
Andy McFadden13a082e2012-08-24 10:16:42 -07002481void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002482 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002483 Vector<ComposerState> state;
2484 Vector<DisplayState> displays;
2485 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002486 d.what = DisplayState::eDisplayProjectionChanged |
2487 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002488 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002489 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002490 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002491 d.frame.makeInvalid();
2492 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002493 d.width = 0;
2494 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002495 displays.add(d);
2496 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002497 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002498
Dan Stoza9e56aa02015-11-02 13:00:03 -08002499 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2500 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002501 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002502}
2503
2504void SurfaceFlinger::initializeDisplays() {
2505 class MessageScreenInitialized : public MessageBase {
2506 SurfaceFlinger* flinger;
2507 public:
2508 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2509 virtual bool handler() {
2510 flinger->onInitializeDisplays();
2511 return true;
2512 }
2513 };
2514 sp<MessageBase> msg = new MessageScreenInitialized(this);
2515 postMessageAsync(msg); // we may be called from main thread, use async message
2516}
2517
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002518void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2519 int mode) {
2520 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2521 this);
2522 int32_t type = hw->getDisplayType();
2523 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002524
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002525 if (mode == currentMode) {
2526 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002527 return;
2528 }
2529
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002530 hw->setPowerMode(mode);
2531 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2532 ALOGW("Trying to set power mode for virtual display");
2533 return;
2534 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002535
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002536 if (currentMode == HWC_POWER_MODE_OFF) {
2537 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002538 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2539 // FIXME: eventthread only knows about the main display right now
2540 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002541 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002543
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002544 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002545 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002546 repaintEverything();
2547 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002548 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002549 disableHardwareVsync(true); // also cancels any in-progress resync
2550
Mathias Agopiancde87a32012-09-13 14:09:01 -07002551 // FIXME: eventthread only knows about the main display right now
2552 mEventThread->onScreenReleased();
2553 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002554
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002555 getHwComposer().setPowerMode(type, mode);
2556 mVisibleRegionsDirty = true;
2557 // from this point on, SF will stop drawing on this display
2558 } else {
2559 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002560 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002561}
2562
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002563void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2564 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002565 SurfaceFlinger& mFlinger;
2566 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002567 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002568 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002569 MessageSetPowerMode(SurfaceFlinger& flinger,
2570 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2571 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002572 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002573 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002574 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002575 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002576 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002577 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002578 ALOGW("Attempt to set power mode = %d for virtual display",
2579 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002580 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002581 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002582 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002583 return true;
2584 }
2585 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002586 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002587 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002588}
2589
2590// ---------------------------------------------------------------------------
2591
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2593{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002595
Mathias Agopianbd115332013-04-18 16:41:04 -07002596 IPCThreadState* ipc = IPCThreadState::self();
2597 const int pid = ipc->getCallingPid();
2598 const int uid = ipc->getCallingUid();
2599 if ((uid != AID_SHELL) &&
2600 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002601 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002602 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002603 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002604 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002605 // (this would indicate SF is stuck, but we want to be able to
2606 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002607 status_t err = mStateLock.timedLock(s2ns(1));
2608 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002609 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002610 result.appendFormat(
2611 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2612 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002613 }
2614
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002615 bool dumpAll = true;
2616 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002617 size_t numArgs = args.size();
2618 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002619 if ((index < numArgs) &&
2620 (args[index] == String16("--list"))) {
2621 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002622 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002623 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002624 }
2625
2626 if ((index < numArgs) &&
2627 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002628 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002629 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002630 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002631 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002632
2633 if ((index < numArgs) &&
2634 (args[index] == String16("--latency-clear"))) {
2635 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002636 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002637 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002638 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002639
2640 if ((index < numArgs) &&
2641 (args[index] == String16("--dispsync"))) {
2642 index++;
2643 mPrimaryDispSync.dump(result);
2644 dumpAll = false;
2645 }
Dan Stozab90cf072015-03-05 11:05:59 -08002646
2647 if ((index < numArgs) &&
2648 (args[index] == String16("--static-screen"))) {
2649 index++;
2650 dumpStaticScreenStats(result);
2651 dumpAll = false;
2652 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002653
2654 if ((index < numArgs) &&
2655 (args[index] == String16("--fences"))) {
2656 index++;
2657 mFenceTracker.dump(&result);
2658 dumpAll = false;
2659 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002661
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002662 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002663 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002664 }
2665
Mathias Agopian9795c422009-08-26 16:36:26 -07002666 if (locked) {
2667 mStateLock.unlock();
2668 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002669 }
2670 write(fd, result.string(), result.size());
2671 return NO_ERROR;
2672}
2673
Dan Stozac7014012014-02-14 15:03:43 -08002674void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2675 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002676{
2677 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2678 const size_t count = currentLayers.size();
2679 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002680 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002681 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002682 }
2683}
2684
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002685void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002686 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002687{
2688 String8 name;
2689 if (index < args.size()) {
2690 name = String8(args[index]);
2691 index++;
2692 }
2693
Dan Stoza9e56aa02015-11-02 13:00:03 -08002694 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2695 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002696 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002697
2698 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002699 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002700 } else {
2701 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2702 const size_t count = currentLayers.size();
2703 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002704 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002705 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002706 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002707 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002708 }
2709 }
2710}
2711
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002712void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002713 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002714{
2715 String8 name;
2716 if (index < args.size()) {
2717 name = String8(args[index]);
2718 index++;
2719 }
2720
2721 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2722 const size_t count = currentLayers.size();
2723 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002724 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002725 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002726 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002727 }
2728 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002729
Svetoslavd85084b2014-03-20 10:28:31 -07002730 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002731}
2732
Jamie Gennis6547ff42013-07-16 20:12:42 -07002733// This should only be called from the main thread. Otherwise it would need
2734// the lock and should use mCurrentState rather than mDrawingState.
2735void SurfaceFlinger::logFrameStats() {
2736 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2737 const size_t count = drawingLayers.size();
2738 for (size_t i=0 ; i<count ; i++) {
2739 const sp<Layer>& layer(drawingLayers[i]);
2740 layer->logFrameStats();
2741 }
2742
2743 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2744}
2745
Andy McFadden4803b742012-09-24 19:07:20 -07002746/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2747{
2748 static const char* config =
2749 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002750#ifdef HAS_CONTEXT_PRIORITY
2751 " HAS_CONTEXT_PRIORITY"
2752#endif
2753#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2754 " NEVER_DEFAULT_TO_ASYNC_MODE"
2755#endif
2756#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2757 " TARGET_DISABLE_TRIPLE_BUFFERING"
2758#endif
2759 "]";
2760 result.append(config);
2761}
2762
Dan Stozab90cf072015-03-05 11:05:59 -08002763void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2764{
2765 result.appendFormat("Static screen stats:\n");
2766 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2767 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2768 float percent = 100.0f *
2769 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2770 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2771 b + 1, bucketTimeSec, percent);
2772 }
2773 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2774 float percent = 100.0f *
2775 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2776 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2777 NUM_BUCKETS - 1, bucketTimeSec, percent);
2778}
2779
Dan Stozae77c7662016-05-13 11:37:28 -07002780void SurfaceFlinger::recordBufferingStats(const char* layerName,
2781 std::vector<OccupancyTracker::Segment>&& history) {
2782 Mutex::Autolock lock(mBufferingStatsMutex);
2783 auto& stats = mBufferingStats[layerName];
2784 for (const auto& segment : history) {
2785 if (!segment.usedThirdBuffer) {
2786 stats.twoBufferTime += segment.totalTime;
2787 }
2788 if (segment.occupancyAverage < 1.0f) {
2789 stats.doubleBufferedTime += segment.totalTime;
2790 } else if (segment.occupancyAverage < 2.0f) {
2791 stats.tripleBufferedTime += segment.totalTime;
2792 }
2793 ++stats.numSegments;
2794 stats.totalTime += segment.totalTime;
2795 }
2796}
2797
2798void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2799 result.append("Buffering stats:\n");
2800 result.append(" [Layer name] <Active time> <Two buffer> "
2801 "<Double buffered> <Triple buffered>\n");
2802 Mutex::Autolock lock(mBufferingStatsMutex);
2803 typedef std::tuple<std::string, float, float, float> BufferTuple;
2804 std::map<float, BufferTuple, std::greater<float>> sorted;
2805 for (const auto& statsPair : mBufferingStats) {
2806 const char* name = statsPair.first.c_str();
2807 const BufferingStats& stats = statsPair.second;
2808 if (stats.numSegments == 0) {
2809 continue;
2810 }
2811 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2812 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2813 stats.totalTime;
2814 float doubleBufferRatio = static_cast<float>(
2815 stats.doubleBufferedTime) / stats.totalTime;
2816 float tripleBufferRatio = static_cast<float>(
2817 stats.tripleBufferedTime) / stats.totalTime;
2818 sorted.insert({activeTime, {name, twoBufferRatio,
2819 doubleBufferRatio, tripleBufferRatio}});
2820 }
2821 for (const auto& sortedPair : sorted) {
2822 float activeTime = sortedPair.first;
2823 const BufferTuple& values = sortedPair.second;
2824 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2825 std::get<0>(values).c_str(), activeTime,
2826 std::get<1>(values), std::get<2>(values),
2827 std::get<3>(values));
2828 }
2829 result.append("\n");
2830}
2831
2832
Mathias Agopian74d211a2013-04-22 16:55:35 +02002833void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2834 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002835{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002836 bool colorize = false;
2837 if (index < args.size()
2838 && (args[index] == String16("--color"))) {
2839 colorize = true;
2840 index++;
2841 }
2842
2843 Colorizer colorizer(colorize);
2844
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002845 // figure out if we're stuck somewhere
2846 const nsecs_t now = systemTime();
2847 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2848 const nsecs_t inTransaction(mDebugInTransaction);
2849 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2850 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2851
2852 /*
Andy McFadden4803b742012-09-24 19:07:20 -07002853 * Dump library configuration.
2854 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002855
2856 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002857 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002858 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07002859 appendSfConfigString(result);
2860 appendUiConfigString(result);
2861 appendGuiConfigString(result);
2862 result.append("\n");
2863
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002864 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002865 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002866 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07002867 result.append(SyncFeatures::getInstance().toString());
2868 result.append("\n");
2869
Dan Stoza9e56aa02015-11-02 13:00:03 -08002870 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2871
Andy McFadden41d67d72014-04-25 16:58:34 -07002872 colorizer.bold(result);
2873 result.append("DispSync configuration: ");
2874 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07002875 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2876 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002877 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
2878 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07002879 result.append("\n");
2880
Dan Stozab90cf072015-03-05 11:05:59 -08002881 // Dump static screen stats
2882 result.append("\n");
2883 dumpStaticScreenStats(result);
2884 result.append("\n");
2885
Dan Stozae77c7662016-05-13 11:37:28 -07002886 dumpBufferingStats(result);
2887
Andy McFadden4803b742012-09-24 19:07:20 -07002888 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002889 * Dump the visible layer list
2890 */
2891 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2892 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002893 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002894 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002895 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002896 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002897 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002898 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002899 }
2900
2901 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002902 * Dump Display state
2903 */
2904
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002905 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08002906 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002907 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002908 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2909 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002910 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07002911 }
2912
2913 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002914 * Dump SurfaceFlinger global state
2915 */
2916
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002917 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002918 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002919 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002920
Mathias Agopian888c8222012-08-04 21:10:38 -07002921 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07002922 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07002923
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002924 colorizer.bold(result);
2925 result.appendFormat("EGL implementation : %s\n",
2926 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2927 colorizer.reset(result);
2928 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07002929 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07002930
Mathias Agopian875d8e12013-06-07 15:35:48 -07002931 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002932
Mathias Agopian42977342012-08-05 00:40:46 -07002933 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002934 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2935 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02002936 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002937 " last eglSwapBuffers() time: %f us\n"
2938 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002939 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002940 " refresh-rate : %f fps\n"
2941 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002942 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07002943 " gpu_to_cpu_unsupported : %d\n"
2944 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002945 mLastSwapBufferTime/1000.0,
2946 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08002947 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08002948 1e9 / activeConfig->getVsyncPeriod(),
2949 activeConfig->getDpiX(),
2950 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07002951 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002952
Mathias Agopian74d211a2013-04-22 16:55:35 +02002953 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002954 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002955
Mathias Agopian74d211a2013-04-22 16:55:35 +02002956 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002957 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002958
2959 /*
2960 * VSYNC state
2961 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02002962 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002963
2964 /*
2965 * Dump HWComposer state
2966 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002967 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002968 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002969 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002970 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08002971 result.appendFormat(" h/w composer %s\n",
2972 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02002973 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002974
2975 /*
2976 * Dump gralloc state
2977 */
2978 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2979 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002980}
2981
Mathias Agopian13127d82013-03-05 17:47:11 -08002982const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07002983SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002984 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07002985 wp<IBinder> dpy;
2986 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2987 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2988 dpy = mDisplays.keyAt(i);
2989 break;
2990 }
2991 }
2992 if (dpy == NULL) {
2993 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2994 // Just use the primary display so we have something to return
2995 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2996 }
2997 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07002998}
2999
Keun young Park63f165f2012-08-31 10:53:36 -07003000bool SurfaceFlinger::startDdmConnection()
3001{
3002 void* libddmconnection_dso =
3003 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3004 if (!libddmconnection_dso) {
3005 return false;
3006 }
3007 void (*DdmConnection_start)(const char* name);
3008 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003009 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003010 if (!DdmConnection_start) {
3011 dlclose(libddmconnection_dso);
3012 return false;
3013 }
3014 (*DdmConnection_start)(getServiceName());
3015 return true;
3016}
3017
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003018status_t SurfaceFlinger::onTransact(
3019 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3020{
3021 switch (code) {
3022 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003023 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003024 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003025 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003026 case CLEAR_ANIMATION_FRAME_STATS:
3027 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003028 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003029 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003030 {
3031 // codes that require permission check
3032 IPCThreadState* ipc = IPCThreadState::self();
3033 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003034 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003035 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003036 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003037 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003038 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3039 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003041 break;
3042 }
3043 case CAPTURE_SCREEN:
3044 {
3045 // codes that require permission check
3046 IPCThreadState* ipc = IPCThreadState::self();
3047 const int pid = ipc->getCallingPid();
3048 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003049 if ((uid != AID_GRAPHICS) &&
3050 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003051 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003052 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3053 return PERMISSION_DENIED;
3054 }
3055 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003056 }
3057 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003058
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003059 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3060 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003061 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003062 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003063 IPCThreadState* ipc = IPCThreadState::self();
3064 const int pid = ipc->getCallingPid();
3065 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003066 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003067 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003068 return PERMISSION_DENIED;
3069 }
3070 int n;
3071 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003072 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003073 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074 return NO_ERROR;
3075 case 1002: // SHOW_UPDATES
3076 n = data.readInt32();
3077 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003078 invalidateHwcGeometry();
3079 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003081 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003082 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003083 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003085 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003086 setTransactionFlags(
3087 eTransactionNeeded|
3088 eDisplayTransactionNeeded|
3089 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003090 return NO_ERROR;
3091 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003092 case 1006:{ // send empty update
3093 signalRefresh();
3094 return NO_ERROR;
3095 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003096 case 1008: // toggle use of hw composer
3097 n = data.readInt32();
3098 mDebugDisableHWC = n ? 1 : 0;
3099 invalidateHwcGeometry();
3100 repaintEverything();
3101 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003102 case 1009: // toggle use of transform hint
3103 n = data.readInt32();
3104 mDebugDisableTransformHint = n ? 1 : 0;
3105 invalidateHwcGeometry();
3106 repaintEverything();
3107 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003108 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003109 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003110 reply->writeInt32(0);
3111 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003112 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003113 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003114 return NO_ERROR;
3115 case 1013: {
3116 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003117 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3118 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003119 return NO_ERROR;
3120 }
3121 case 1014: {
3122 // daltonize
3123 n = data.readInt32();
3124 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003125 case 1:
3126 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3127 break;
3128 case 2:
3129 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3130 break;
3131 case 3:
3132 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3133 break;
3134 default:
3135 mDaltonizer.setType(ColorBlindnessType::None);
3136 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003137 }
3138 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003139 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003140 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003141 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003142 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003143 invalidateHwcGeometry();
3144 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003145 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003147 case 1015: {
3148 // apply a color matrix
3149 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003150 if (n) {
3151 // color matrix is sent as mat3 matrix followed by vec3
3152 // offset, then packed into a mat4 where the last row is
3153 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003154 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003155 for (size_t j = 0; j < 4; j++) {
3156 mColorMatrix[i][j] = data.readFloat();
3157 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003158 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003159 } else {
3160 mColorMatrix = mat4();
3161 }
3162 invalidateHwcGeometry();
3163 repaintEverything();
3164 return NO_ERROR;
3165 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003166 // This is an experimental interface
3167 // Needs to be shifted to proper binder interface when we productize
3168 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003169 n = data.readInt32();
3170 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003171 return NO_ERROR;
3172 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003173 case 1017: {
3174 n = data.readInt32();
3175 mForceFullDamage = static_cast<bool>(n);
3176 return NO_ERROR;
3177 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003178 case 1018: { // Modify Choreographer's phase offset
3179 n = data.readInt32();
3180 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3181 return NO_ERROR;
3182 }
3183 case 1019: { // Modify SurfaceFlinger's phase offset
3184 n = data.readInt32();
3185 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3186 return NO_ERROR;
3187 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003188 }
3189 }
3190 return err;
3191}
3192
Mathias Agopian53331da2011-08-22 21:44:41 -07003193void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003194 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003195 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003196}
3197
Mathias Agopian59119e62010-10-11 12:37:43 -07003198// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003199// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003200// ---------------------------------------------------------------------------
3201
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003202/* The code below is here to handle b/8734824
3203 *
3204 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003205 * from the surfaceflinger thread to the calling binder thread, where they
3206 * are executed. This allows the calling thread in the calling process to be
3207 * reused and not depend on having "enough" binder threads to handle the
3208 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003209 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003210class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003211 /* Parts of GraphicProducerWrapper are run on two different threads,
3212 * communicating by sending messages via Looper but also by shared member
3213 * data. Coherence maintenance is subtle and in places implicit (ugh).
3214 *
3215 * Don't rely on Looper's sendMessage/handleMessage providing
3216 * release/acquire semantics for any data not actually in the Message.
3217 * Data going from surfaceflinger to binder threads needs to be
3218 * synchronized explicitly.
3219 *
3220 * Barrier open/wait do provide release/acquire semantics. This provides
3221 * implicit synchronization for data coming back from binder to
3222 * surfaceflinger threads.
3223 */
3224
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003225 sp<IGraphicBufferProducer> impl;
3226 sp<Looper> looper;
3227 status_t result;
3228 bool exitPending;
3229 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003230 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003231 uint32_t code;
3232 Parcel const* data;
3233 Parcel* reply;
3234
3235 enum {
3236 MSG_API_CALL,
3237 MSG_EXIT
3238 };
3239
3240 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003241 * Called on surfaceflinger thread. This is called by our "fake"
3242 * BpGraphicBufferProducer. We package the data and reply Parcel and
3243 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003244 */
3245 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003246 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003247 this->code = code;
3248 this->data = &data;
3249 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003250 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003251 // if we've exited, we run the message synchronously right here.
3252 // note (JH): as far as I can tell from looking at the code, this
3253 // never actually happens. if it does, i'm not sure if it happens
3254 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003255 handleMessage(Message(MSG_API_CALL));
3256 } else {
3257 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003258 // Prevent stores to this->{code, data, reply} from being
3259 // reordered later than the construction of Message.
3260 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003261 looper->sendMessage(this, Message(MSG_API_CALL));
3262 barrier.wait();
3263 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003264 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003265 }
3266
3267 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003268 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003269 * call the real BpGraphicBufferProducer.
3270 */
3271 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003272 int what = message.what;
3273 // Prevent reads below from happening before the read from Message
3274 atomic_thread_fence(memory_order_acquire);
3275 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003276 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003277 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003278 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003279 exitRequested = true;
3280 }
3281 }
3282
3283public:
Jesse Hallb154c422014-07-13 12:47:02 -07003284 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3285 : impl(impl),
3286 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003287 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003288 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003289 exitRequested(false),
3290 code(0),
3291 data(NULL),
3292 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003293 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003294
Jesse Hallb154c422014-07-13 12:47:02 -07003295 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003296 status_t waitForResponse() {
3297 do {
3298 looper->pollOnce(-1);
3299 } while (!exitRequested);
3300 return result;
3301 }
3302
Jesse Hallb154c422014-07-13 12:47:02 -07003303 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003304 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003305 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003306 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003307 // Ensure this->result is visible to the binder thread before it
3308 // handles the message.
3309 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003310 looper->sendMessage(this, Message(MSG_EXIT));
3311 }
3312};
3313
3314
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003315status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3316 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003317 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003318 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003319 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003320
3321 if (CC_UNLIKELY(display == 0))
3322 return BAD_VALUE;
3323
3324 if (CC_UNLIKELY(producer == 0))
3325 return BAD_VALUE;
3326
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003327 // if we have secure windows on this display, never allow the screen capture
3328 // unless the producer interface is local (i.e.: we can take a screenshot for
3329 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003330 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003331
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003332 // Convert to surfaceflinger's internal rotation type.
3333 Transform::orientation_flags rotationFlags;
3334 switch (rotation) {
3335 case ISurfaceComposer::eRotateNone:
3336 rotationFlags = Transform::ROT_0;
3337 break;
3338 case ISurfaceComposer::eRotate90:
3339 rotationFlags = Transform::ROT_90;
3340 break;
3341 case ISurfaceComposer::eRotate180:
3342 rotationFlags = Transform::ROT_180;
3343 break;
3344 case ISurfaceComposer::eRotate270:
3345 rotationFlags = Transform::ROT_270;
3346 break;
3347 default:
3348 rotationFlags = Transform::ROT_0;
3349 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3350 break;
3351 }
3352
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003353 class MessageCaptureScreen : public MessageBase {
3354 SurfaceFlinger* flinger;
3355 sp<IBinder> display;
3356 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003357 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003358 uint32_t reqWidth, reqHeight;
3359 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003360 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003361 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003362 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003363 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003364 public:
3365 MessageCaptureScreen(SurfaceFlinger* flinger,
3366 const sp<IBinder>& display,
3367 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003368 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003369 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003370 bool useIdentityTransform,
3371 Transform::orientation_flags rotation,
3372 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003373 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003374 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003375 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003376 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003377 rotation(rotation), result(PERMISSION_DENIED),
3378 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003379 {
3380 }
3381 status_t getResult() const {
3382 return result;
3383 }
3384 virtual bool handler() {
3385 Mutex::Autolock _l(flinger->mStateLock);
3386 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003387 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003388 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003389 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003390 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003391 return true;
3392 }
3393 };
3394
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003395 // this creates a "fake" BBinder which will serve as a "fake" remote
3396 // binder to receive the marshaled calls and forward them to the
3397 // real remote (a BpGraphicBufferProducer)
3398 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3399
3400 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3401 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003402 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003403 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003404 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003405 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003406
3407 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003408 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003409 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003410 }
3411 return res;
3412}
3413
Mathias Agopian180f10d2013-04-10 22:55:41 -07003414
3415void SurfaceFlinger::renderScreenImplLocked(
3416 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003417 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003418 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003419 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003420{
3421 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003422 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003423
3424 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003425 const int32_t hw_w = hw->getWidth();
3426 const int32_t hw_h = hw->getHeight();
3427 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003428 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003429
Dan Stozac1879002014-05-22 15:59:05 -07003430 // if a default or invalid sourceCrop is passed in, set reasonable values
3431 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3432 !sourceCrop.isValid()) {
3433 sourceCrop.setLeftTop(Point(0, 0));
3434 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3435 }
3436
3437 // ensure that sourceCrop is inside screen
3438 if (sourceCrop.left < 0) {
3439 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3440 }
Dan Stozabe31f442014-06-11 11:20:54 -07003441 if (sourceCrop.right > hw_w) {
3442 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003443 }
3444 if (sourceCrop.top < 0) {
3445 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3446 }
Dan Stozabe31f442014-06-11 11:20:54 -07003447 if (sourceCrop.bottom > hw_h) {
3448 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003449 }
3450
Mathias Agopian180f10d2013-04-10 22:55:41 -07003451 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003452 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003453
3454 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003455 engine.setViewportAndProjection(
3456 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003457 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003458
3459 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003460 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003461
3462 const LayerVector& layers( mDrawingState.layersSortedByZ );
3463 const size_t count = layers.size();
3464 for (size_t i=0 ; i<count ; ++i) {
3465 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003466 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003467 if (state.layerStack == hw->getLayerStack()) {
3468 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3469 if (layer->isVisible()) {
3470 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003471 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003472 if (filtering) layer->setFiltering(false);
3473 }
3474 }
3475 }
3476 }
3477
Mathias Agopian931bda12013-08-28 18:11:46 -07003478 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003479}
3480
3481
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003482status_t SurfaceFlinger::captureScreenImplLocked(
3483 const sp<const DisplayDevice>& hw,
3484 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003485 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003486 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003487 bool useIdentityTransform, Transform::orientation_flags rotation,
3488 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003489{
3490 ATRACE_CALL();
3491
Mathias Agopian180f10d2013-04-10 22:55:41 -07003492 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003493 uint32_t hw_w = hw->getWidth();
3494 uint32_t hw_h = hw->getHeight();
3495
3496 if (rotation & Transform::ROT_90) {
3497 std::swap(hw_w, hw_h);
3498 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003499
Mathias Agopian180f10d2013-04-10 22:55:41 -07003500 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3501 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3502 reqWidth, reqHeight, hw_w, hw_h);
3503 return BAD_VALUE;
3504 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003505
Mathias Agopian180f10d2013-04-10 22:55:41 -07003506 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3507 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3508
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003509 bool secureLayerIsVisible = false;
3510 const LayerVector& layers(mDrawingState.layersSortedByZ);
3511 const size_t count = layers.size();
3512 for (size_t i = 0 ; i < count ; ++i) {
3513 const sp<Layer>& layer(layers[i]);
3514 const Layer::State& state(layer->getDrawingState());
3515 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3516 state.z <= maxLayerZ && layer->isVisible() &&
3517 layer->isSecure()) {
3518 secureLayerIsVisible = true;
3519 }
3520 }
3521
3522 if (!isLocalScreenshot && secureLayerIsVisible) {
3523 ALOGW("FB is protected: PERMISSION_DENIED");
3524 return PERMISSION_DENIED;
3525 }
3526
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003527 // create a surface (because we're a producer, and we need to
3528 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003529 sp<Surface> sur = new Surface(producer, false);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003530 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003531
Michael Lentine5a16a622015-05-21 13:48:24 -07003532 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3533 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003534 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3535 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003536
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003537 int err = 0;
3538 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003539 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003540 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3541 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003542
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003543 if (err == NO_ERROR) {
3544 ANativeWindowBuffer* buffer;
3545 /* TODO: Once we have the sync framework everywhere this can use
3546 * server-side waits on the fence that dequeueBuffer returns.
3547 */
3548 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3549 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003550 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003551 // create an EGLImage from the buffer so we can later
3552 // turn it into a texture
3553 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3554 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3555 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003556 // this binds the given EGLImage as a framebuffer for the
3557 // duration of this scope.
3558 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3559 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003560 // this will in fact render into our dequeued buffer
3561 // via an FBO, which means we didn't have to create
3562 // an EGLSurface and therefore we're not
3563 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003564 renderScreenImplLocked(
3565 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3566 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003567
Riley Andrews86639902014-08-15 12:27:24 -07003568 // Attempt to create a sync khr object that can produce a sync point. If that
3569 // isn't available, create a non-dupable sync object in the fallback path and
3570 // wait on it directly.
3571 EGLSyncKHR sync;
3572 if (!DEBUG_SCREENSHOTS) {
3573 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003574 // native fence fd will not be populated until flush() is done.
3575 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003576 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003577 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003578 }
Riley Andrews86639902014-08-15 12:27:24 -07003579 if (sync != EGL_NO_SYNC_KHR) {
3580 // get the sync fd
3581 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3582 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3583 ALOGW("captureScreen: failed to dup sync khr object");
3584 syncFd = -1;
3585 }
3586 eglDestroySyncKHR(mEGLDisplay, sync);
3587 } else {
3588 // fallback path
3589 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3590 if (sync != EGL_NO_SYNC_KHR) {
3591 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3592 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3593 EGLint eglErr = eglGetError();
3594 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3595 ALOGW("captureScreen: fence wait timed out");
3596 } else {
3597 ALOGW_IF(eglErr != EGL_SUCCESS,
3598 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3599 }
3600 eglDestroySyncKHR(mEGLDisplay, sync);
3601 } else {
3602 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3603 }
3604 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003605 if (DEBUG_SCREENSHOTS) {
3606 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3607 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3608 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3609 hw, minLayerZ, maxLayerZ);
3610 delete [] pixels;
3611 }
3612
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003613 } else {
3614 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3615 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003616 window->cancelBuffer(window, buffer, syncFd);
3617 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003618 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003619 // destroy our image
3620 eglDestroyImageKHR(mEGLDisplay, image);
3621 } else {
3622 result = BAD_VALUE;
3623 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003624 if (buffer) {
3625 // queueBuffer takes ownership of syncFd
3626 result = window->queueBuffer(window, buffer, syncFd);
3627 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003628 }
3629 } else {
3630 result = BAD_VALUE;
3631 }
3632 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3633 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003634
Mathias Agopian74c40c02010-09-29 13:02:36 -07003635 return result;
3636}
3637
Mathias Agopiand5556842013-09-19 17:08:37 -07003638void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3639 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003640 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003641 for (size_t y=0 ; y<h ; y++) {
3642 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3643 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003644 if (p[x] != 0xFF000000) return;
3645 }
3646 }
3647 ALOGE("*** we just took a black screenshot ***\n"
3648 "requested minz=%d, maxz=%d, layerStack=%d",
3649 minLayerZ, maxLayerZ, hw->getLayerStack());
3650 const LayerVector& layers( mDrawingState.layersSortedByZ );
3651 const size_t count = layers.size();
3652 for (size_t i=0 ; i<count ; ++i) {
3653 const sp<Layer>& layer(layers[i]);
3654 const Layer::State& state(layer->getDrawingState());
3655 const bool visible = (state.layerStack == hw->getLayerStack())
3656 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3657 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003658 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003659 visible ? '+' : '-',
3660 i, layer->getName().string(), state.layerStack, state.z,
3661 layer->isVisible(), state.flags, state.alpha);
3662 }
3663 }
3664}
3665
Pablo Ceballosce796e72016-02-04 19:10:51 -08003666bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3667 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3668 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3669}
3670
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003671// ---------------------------------------------------------------------------
3672
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003673SurfaceFlinger::LayerVector::LayerVector() {
3674}
3675
3676SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003677 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003678}
3679
3680int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3681 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003682{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003683 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003684 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3685 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003686
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003687 uint32_t ls = l->getCurrentState().layerStack;
3688 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003689 if (ls != rs)
3690 return ls - rs;
3691
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003692 uint32_t lz = l->getCurrentState().z;
3693 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003694 if (lz != rz)
3695 return lz - rz;
3696
3697 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003698}
3699
3700// ---------------------------------------------------------------------------
3701
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003702SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003703 : type(DisplayDevice::DISPLAY_ID_INVALID),
3704 layerStack(DisplayDevice::NO_LAYER_STACK),
3705 orientation(0),
3706 width(0),
3707 height(0),
3708 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003709}
3710
Pablo Ceballos53390e12015-08-04 11:25:59 -07003711SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3712 DisplayDevice::DisplayType type, bool isSecure)
3713 : type(type),
3714 layerStack(DisplayDevice::NO_LAYER_STACK),
3715 orientation(0),
3716 width(0),
3717 height(0),
3718 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003719 viewport.makeInvalid();
3720 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003721}
3722
3723// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003726
3727
3728#if defined(__gl_h_)
3729#error "don't include gl/gl.h in this file"
3730#endif
3731
3732#if defined(__gl2_h_)
3733#error "don't include gl2/gl2.h in this file"
3734#endif