blob: 2cf8fb2301b972ba11da71fdba8842febbb71975 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080022#include <errno.h>
23#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070024#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070025#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080026#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070027#include <stdatomic.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070028
29#include <EGL/egl.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080030
31#include <cutils/log.h>
32#include <cutils/properties.h>
33
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070036#include <binder/MemoryHeapBase.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070037#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070038
Mathias Agopianc666cae2012-07-25 18:56:13 -070039#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070040#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070041
Mathias Agopian921e6ac2012-07-23 23:11:29 -070042#include <gui/BitTube.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070043#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070044#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/IDisplayEventConnection.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080046#include <gui/Surface.h>
Jamie Gennis392edd82012-11-29 23:26:29 -080047#include <gui/GraphicBufferAlloc.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070048
49#include <ui/GraphicBufferAllocator.h>
50#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080052
Mathias Agopiancde87a32012-09-13 14:09:01 -070053#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080054#include <utils/String8.h>
55#include <utils/String16.h>
56#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070057#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080058#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080059
Mathias Agopian921e6ac2012-07-23 23:11:29 -070060#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070061#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080062
Mathias Agopian3e25fd82013-04-22 17:52:16 +020063#include "Client.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064#include "clz.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020065#include "Colorizer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080066#include "DdmConnection.h"
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -070067#include "DisplayDevice.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070068#include "DispSync.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070069#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080070#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include "Layer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080072#include "LayerDim.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080073#include "SurfaceFlinger.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Mathias Agopiana4912602012-07-12 14:25:33 -070075#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070076#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070077#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Mathias Agopianff2ed702013-09-01 21:36:12 -070079#include "Effects/Daltonizer.h"
80
Mathias Agopian875d8e12013-06-07 15:35:48 -070081#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070082#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070083
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080084#define DISPLAY_COUNT 1
85
Mathias Agopianfee2b462013-07-03 12:34:01 -070086/*
87 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
88 * black pixels.
89 */
90#define DEBUG_SCREENSHOTS false
91
Mathias Agopianca088332013-03-28 17:44:13 -070092EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93
Evgenii Stepanov22819272016-07-14 14:17:24 -070094// Workaround for b/30067360: /proc/self/environ inaccessible in SurfaceFlinger
95// => ASan fails to read ASAN_OPTIONS => alloc-dealloc-mismatch bug is not
96// suppressed and prevents the device from booting.
97#ifndef __has_feature
98#define __has_feature(x) 0
99#endif
100#if __has_feature(address_sanitizer)
101__attribute__((visibility("default")))
102extern "C" const char* __asan_default_options() {
103 return "alloc_dealloc_mismatch=0";
104}
105#endif
106
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800107namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700108
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700109// This is the phase offset in nanoseconds of the software vsync event
110// relative to the vsync event reported by HWComposer. The software vsync
111// event is when SurfaceFlinger and Choreographer-based applications run each
112// frame.
113//
114// This phase offset allows adjustment of the minimum latency from application
115// wake-up (by Choregographer) time to the time at which the resulting window
116// image is displayed. This value may be either positive (after the HW vsync)
117// or negative (before the HW vsync). Setting it to 0 will result in a
118// minimum latency of two vsync periods because the app and SurfaceFlinger
119// will run just after the HW vsync. Setting it to a positive number will
120// result in the minimum latency being:
121//
122// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
123//
124// Note that reducing this latency makes it more likely for the applications
125// to not have their window content image ready in time. When this happens
126// the latency will end up being an additional vsync period, and animations
127// will hiccup. Therefore, this latency should be tuned somewhat
128// conservatively (or at least with awareness of the trade-off being made).
129static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
130
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700131// This is the phase offset at which SurfaceFlinger's composition runs.
132static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
133
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800134// ---------------------------------------------------------------------------
135
Mathias Agopian99b49842011-06-27 16:05:52 -0700136const String16 sHardwareTest("android.permission.HARDWARE_TEST");
137const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
138const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
139const String16 sDump("android.permission.DUMP");
140
141// ---------------------------------------------------------------------------
142
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800143SurfaceFlinger::SurfaceFlinger()
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700144 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800145 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700146 mTransactionPending(false),
147 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700148 mLayersRemoved(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700149 mRepaintEverything(0),
Mathias Agopian875d8e12013-06-07 15:35:48 -0700150 mRenderEngine(NULL),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800151 mBootTime(systemTime()),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800152 mBuiltinDisplays(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800153 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800154 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800155 mAnimCompositionPending(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800156 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700157 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700158 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700159 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700160 mDebugInSwapBuffers(0),
161 mLastSwapBufferTime(0),
162 mDebugInTransaction(0),
163 mLastTransactionTime(0),
Mathias Agopianff2ed702013-09-01 21:36:12 -0700164 mBootFinished(false),
Dan Stozaee44edd2015-03-23 15:50:23 -0700165 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700166 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000167 mPrimaryDispSync("PrimaryDispSync"),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700168 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700169 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800170 mHasColorMatrix(false),
171 mHasPoweredOff(false),
172 mFrameBuckets(),
173 mTotalTime(0),
174 mLastSwapTime(0)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800175{
Steve Blocka19954a2012-01-04 20:05:49 +0000176 ALOGI("SurfaceFlinger is starting");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800177
178 // debugging stuff...
179 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700180
Mathias Agopianb4b17302013-03-20 18:36:41 -0700181 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700182 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700183
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800184 property_get("debug.sf.showupdates", value, "0");
185 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700186
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700187 property_get("debug.sf.ddms", value, "0");
188 mDebugDDMS = atoi(value);
189 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700190 if (!startDdmConnection()) {
191 // start failed, and DDMS debugging not enabled
192 mDebugDDMS = 0;
193 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700194 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700195 ALOGI_IF(mDebugRegion, "showupdates enabled");
196 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700197
198 property_get("debug.sf.disable_backpressure", value, "0");
199 mPropagateBackpressure = !atoi(value);
200 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201}
202
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800203void SurfaceFlinger::onFirstRef()
204{
205 mEventQueue.init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800206}
207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208SurfaceFlinger::~SurfaceFlinger()
209{
Mathias Agopiana4912602012-07-12 14:25:33 -0700210 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
211 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
212 eglTerminate(display);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800213}
214
Dan Stozac7014012014-02-14 15:03:43 -0800215void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800216{
217 // the window manager died on us. prepare its eulogy.
218
Andy McFadden13a082e2012-08-24 10:16:42 -0700219 // restore initial conditions (default device unblank, etc)
220 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800221
222 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700223 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800224}
225
Mathias Agopian7e27f052010-05-28 14:22:23 -0700226sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800227{
Mathias Agopian96f08192010-06-02 23:28:45 -0700228 sp<ISurfaceComposerClient> bclient;
229 sp<Client> client(new Client(this));
230 status_t err = client->initCheck();
231 if (err == NO_ERROR) {
232 bclient = client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800233 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800234 return bclient;
235}
236
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700237sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
238 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700239{
240 class DisplayToken : public BBinder {
241 sp<SurfaceFlinger> flinger;
242 virtual ~DisplayToken() {
243 // no more references, this display must be terminated
244 Mutex::Autolock _l(flinger->mStateLock);
245 flinger->mCurrentState.displays.removeItem(this);
246 flinger->setTransactionFlags(eDisplayTransactionNeeded);
247 }
248 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700249 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700250 : flinger(flinger) {
251 }
252 };
253
254 sp<BBinder> token = new DisplayToken(this);
255
256 Mutex::Autolock _l(mStateLock);
Pablo Ceballos53390e12015-08-04 11:25:59 -0700257 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700258 info.displayName = displayName;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700259 mCurrentState.displays.add(token, info);
260
261 return token;
262}
263
Jesse Hall6c913be2013-08-08 12:15:49 -0700264void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
265 Mutex::Autolock _l(mStateLock);
266
267 ssize_t idx = mCurrentState.displays.indexOfKey(display);
268 if (idx < 0) {
269 ALOGW("destroyDisplay: invalid display token");
270 return;
271 }
272
273 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
274 if (!info.isVirtualDisplay()) {
275 ALOGE("destroyDisplay called for non-virtual display");
276 return;
277 }
278
279 mCurrentState.displays.removeItemsAt(idx);
280 setTransactionFlags(eDisplayTransactionNeeded);
281}
282
Jesse Hall692c7232012-11-08 15:41:56 -0800283void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800284 ALOGV("createBuiltinDisplayLocked(%d)", type);
Jesse Hall692c7232012-11-08 15:41:56 -0800285 ALOGW_IF(mBuiltinDisplays[type],
286 "Overwriting display token for display type %d", type);
287 mBuiltinDisplays[type] = new BBinder();
Jesse Hall692c7232012-11-08 15:41:56 -0800288 // All non-virtual displays are currently considered secure.
Pablo Ceballos53390e12015-08-04 11:25:59 -0700289 DisplayDeviceState info(type, true);
Jesse Hall692c7232012-11-08 15:41:56 -0800290 mCurrentState.displays.add(mBuiltinDisplays[type], info);
291}
292
Mathias Agopiane57f2922012-08-09 16:29:12 -0700293sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700294 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700295 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
296 return NULL;
297 }
Jesse Hall692c7232012-11-08 15:41:56 -0800298 return mBuiltinDisplays[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700299}
300
Jamie Gennis9a78c902011-01-12 18:30:40 -0800301sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
302{
303 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
304 return gba;
305}
Mathias Agopianb7e930d2010-06-01 15:12:58 -0700306
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800307void SurfaceFlinger::bootFinished()
308{
309 const nsecs_t now = systemTime();
310 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000311 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian3330b202009-10-05 17:07:12 -0700312 mBootFinished = true;
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700313
314 // wait patiently for the window manager death
315 const String16 name("window");
316 sp<IBinder> window(defaultServiceManager()->getService(name));
317 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700318 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700319 }
320
321 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700322 // formerly we would just kill the process, but we now ask it to exit so it
323 // can choose where to stop the animation.
324 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700325
326 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
327 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
328 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329}
330
Mathias Agopian3f844832013-08-07 21:24:32 -0700331void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700332 class MessageDestroyGLTexture : public MessageBase {
Mathias Agopian3f844832013-08-07 21:24:32 -0700333 RenderEngine& engine;
334 uint32_t texture;
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700335 public:
Mathias Agopian3f844832013-08-07 21:24:32 -0700336 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
337 : engine(engine), texture(texture) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700338 }
339 virtual bool handler() {
Mathias Agopian3f844832013-08-07 21:24:32 -0700340 engine.deleteTextures(1, &texture);
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700341 return true;
342 }
343 };
Mathias Agopian3f844832013-08-07 21:24:32 -0700344 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700345}
346
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700347class DispSyncSource : public VSyncSource, private DispSync::Callback {
348public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700349 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000350 const char* name) :
351 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700352 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700353 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000354 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
355 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700356 mDispSync(dispSync),
357 mCallbackMutex(),
358 mCallback(),
359 mVsyncMutex(),
360 mPhaseOffset(phaseOffset),
361 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700362
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700363 virtual ~DispSyncSource() {}
364
365 virtual void setVSyncEnabled(bool enable) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700366 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700367 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000368 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700369 static_cast<DispSync::Callback*>(this));
370 if (err != NO_ERROR) {
371 ALOGE("error registering vsync callback: %s (%d)",
372 strerror(-err), err);
373 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700374 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700375 } else {
376 status_t err = mDispSync->removeEventListener(
377 static_cast<DispSync::Callback*>(this));
378 if (err != NO_ERROR) {
379 ALOGE("error unregistering vsync callback: %s (%d)",
380 strerror(-err), err);
381 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700382 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700383 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700384 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700385 }
386
387 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700388 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700389 mCallback = callback;
390 }
391
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700392 virtual void setPhaseOffset(nsecs_t phaseOffset) {
393 Mutex::Autolock lock(mVsyncMutex);
394
395 // Normalize phaseOffset to [0, period)
396 auto period = mDispSync->getPeriod();
397 phaseOffset %= period;
398 if (phaseOffset < 0) {
399 // If we're here, then phaseOffset is in (-period, 0). After this
400 // operation, it will be in (0, period)
401 phaseOffset += period;
402 }
403 mPhaseOffset = phaseOffset;
404
405 // If we're not enabled, we don't need to mess with the listeners
406 if (!mEnabled) {
407 return;
408 }
409
410 // Remove the listener with the old offset
411 status_t err = mDispSync->removeEventListener(
412 static_cast<DispSync::Callback*>(this));
413 if (err != NO_ERROR) {
414 ALOGE("error unregistering vsync callback: %s (%d)",
415 strerror(-err), err);
416 }
417
418 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000419 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700420 static_cast<DispSync::Callback*>(this));
421 if (err != NO_ERROR) {
422 ALOGE("error registering vsync callback: %s (%d)",
423 strerror(-err), err);
424 }
425 }
426
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700427private:
428 virtual void onDispSyncEvent(nsecs_t when) {
429 sp<VSyncSource::Callback> callback;
430 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700431 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700432 callback = mCallback;
433
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700434 if (mTraceVsync) {
435 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700436 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700437 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700438 }
439
440 if (callback != NULL) {
441 callback->onVSyncEvent(when);
442 }
443 }
444
Tim Murray4a4e4a22016-04-19 16:29:23 +0000445 const char* const mName;
446
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700447 int mValue;
448
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700449 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700450 const String8 mVsyncOnLabel;
451 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700452
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700453 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700454
455 Mutex mCallbackMutex; // Protects the following
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700456 sp<VSyncSource::Callback> mCallback;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700457
458 Mutex mVsyncMutex; // Protects the following
459 nsecs_t mPhaseOffset;
460 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700461};
462
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700463class InjectVSyncSource : public VSyncSource {
464public:
465 InjectVSyncSource() {}
466
467 virtual ~InjectVSyncSource() {}
468
469 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
470 std::lock_guard<std::mutex> lock(mCallbackMutex);
471 mCallback = callback;
472 }
473
474 virtual void onInjectSyncEvent(nsecs_t when) {
475 std::lock_guard<std::mutex> lock(mCallbackMutex);
476 mCallback->onVSyncEvent(when);
477 }
478
479 virtual void setVSyncEnabled(bool) {}
480 virtual void setPhaseOffset(nsecs_t) {}
481
482private:
483 std::mutex mCallbackMutex; // Protects the following
484 sp<VSyncSource::Callback> mCallback;
485};
486
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700487void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700488 ALOGI( "SurfaceFlinger's main thread ready to run. "
489 "Initializing graphics H/W...");
490
Dan Stoza9e56aa02015-11-02 13:00:03 -0800491 { // Autolock scope
492 Mutex::Autolock _l(mStateLock);
493
494 // initialize EGL for the default display
495 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
496 eglInitialize(mEGLDisplay, NULL, NULL);
497
498 // start the EventThread
499 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
500 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000501 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800502 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
503 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000504 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800505 mEventQueue.setEventThread(mSFEventThread);
506
Tim Murrayacff43d2016-07-29 13:57:24 -0700507 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700508 struct sched_param param = {0};
509 param.sched_priority = 1;
Tim Murray41a38532016-06-22 12:42:10 -0700510 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
511 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
512 }
513
Dan Stoza9e56aa02015-11-02 13:00:03 -0800514 // Get a RenderEngine for the given display / config (can't fail)
515 mRenderEngine = RenderEngine::create(mEGLDisplay,
516 HAL_PIXEL_FORMAT_RGBA_8888);
517 }
518
519 // Drop the state lock while we initialize the hardware composer. We drop
520 // the lock because on creation, it will call back into SurfaceFlinger to
521 // initialize the primary display.
522 mHwc = new HWComposer(this);
523 mHwc->setEventHandler(static_cast<HWComposer::EventHandler*>(this));
524
Jesse Hall692c7232012-11-08 15:41:56 -0800525 Mutex::Autolock _l(mStateLock);
526
Mathias Agopian875d8e12013-06-07 15:35:48 -0700527 // retrieve the EGL context that was selected/created
528 mEGLContext = mRenderEngine->getEGLContext();
Mathias Agopiana4912602012-07-12 14:25:33 -0700529
Mathias Agopianda27af92012-09-13 18:17:13 -0700530 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
531 "couldn't create EGLContext");
532
Dan Stoza9e56aa02015-11-02 13:00:03 -0800533 // make the GLContext current so that we can create textures when creating
534 // Layers (which may happens before we render something)
Mathias Agopiana6bb1072013-08-07 20:10:20 -0700535 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
536
Jamie Gennisd1700752013-10-14 12:22:52 -0700537 mEventControlThread = new EventControlThread(this);
538 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
539
Mathias Agopian92a979a2012-08-02 18:32:23 -0700540 // initialize our drawing state
541 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700542
Andy McFadden13a082e2012-08-24 10:16:42 -0700543 // set initial conditions (e.g. unblank default device)
544 initializeDisplays();
545
Dan Stoza4e637772016-07-28 13:31:51 -0700546 mRenderEngine->primeCache();
547
Mathias Agopiana1ecca92009-05-21 19:21:59 -0700548 // start boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700549 startBootAnim();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800550
Dan Stoza9e56aa02015-11-02 13:00:03 -0800551 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700552}
553
Mathias Agopiana67e4182012-06-19 17:26:12 -0700554void SurfaceFlinger::startBootAnim() {
555 // start boot animation
556 property_set("service.bootanim.exit", "0");
557 property_set("ctl.start", "bootanim");
558}
559
Mathias Agopian875d8e12013-06-07 15:35:48 -0700560size_t SurfaceFlinger::getMaxTextureSize() const {
561 return mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700562}
563
Mathias Agopian875d8e12013-06-07 15:35:48 -0700564size_t SurfaceFlinger::getMaxViewportDims() const {
565 return mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700566}
567
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800568// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800569
Jamie Gennis582270d2011-08-17 18:19:00 -0700570bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800571 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800572 Mutex::Autolock _l(mStateLock);
Marco Nelissen097ca272014-11-14 08:01:01 -0800573 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Mathias Agopian67106042013-03-14 19:18:13 -0700574 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800575}
576
Dan Stoza7f7da322014-05-02 15:26:25 -0700577status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
578 Vector<DisplayInfo>* configs) {
Tatenda Chipeperekwa23e16bb2014-10-29 16:47:19 -0700579 if ((configs == NULL) || (display.get() == NULL)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700580 return BAD_VALUE;
581 }
582
Naseer Ahmed7aa0c472014-11-03 14:49:23 -0500583 if (!display.get())
584 return NAME_NOT_FOUND;
585
Jesse Hall692c7232012-11-08 15:41:56 -0800586 int32_t type = NAME_NOT_FOUND;
Jesse Hall9e663de2013-08-16 14:28:37 -0700587 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
Jesse Hall692c7232012-11-08 15:41:56 -0800588 if (display == mBuiltinDisplays[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700589 type = i;
590 break;
591 }
592 }
593
594 if (type < 0) {
595 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700596 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700597
Mathias Agopian8b736f12012-08-13 17:54:26 -0700598 // TODO: Not sure if display density should handled by SF any longer
599 class Density {
600 static int getDensityFromProperty(char const* propName) {
601 char property[PROPERTY_VALUE_MAX];
602 int density = 0;
603 if (property_get(propName, property, NULL) > 0) {
604 density = atoi(property);
605 }
606 return density;
607 }
608 public:
609 static int getEmuDensity() {
610 return getDensityFromProperty("qemu.sf.lcd_density"); }
611 static int getBuildDensity() {
612 return getDensityFromProperty("ro.sf.lcd_density"); }
613 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700614
Dan Stoza7f7da322014-05-02 15:26:25 -0700615 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700616
Dan Stoza9e56aa02015-11-02 13:00:03 -0800617 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700618 DisplayInfo info = DisplayInfo();
619
Dan Stoza9e56aa02015-11-02 13:00:03 -0800620 float xdpi = hwConfig->getDpiX();
621 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700622
623 if (type == DisplayDevice::DISPLAY_PRIMARY) {
624 // The density of the device is provided by a build property
625 float density = Density::getBuildDensity() / 160.0f;
626 if (density == 0) {
627 // the build doesn't provide a density -- this is wrong!
628 // use xdpi instead
629 ALOGE("ro.sf.lcd_density must be defined as a build property");
630 density = xdpi / 160.0f;
631 }
632 if (Density::getEmuDensity()) {
633 // if "qemu.sf.lcd_density" is specified, it overrides everything
634 xdpi = ydpi = density = Density::getEmuDensity();
635 density /= 160.0f;
636 }
637 info.density = density;
638
639 // TODO: this needs to go away (currently needed only by webkit)
640 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
641 info.orientation = hw->getOrientation();
642 } else {
643 // TODO: where should this value come from?
644 static const int TV_DENSITY = 213;
645 info.density = TV_DENSITY / 160.0f;
646 info.orientation = 0;
647 }
648
Dan Stoza9e56aa02015-11-02 13:00:03 -0800649 info.w = hwConfig->getWidth();
650 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700651 info.xdpi = xdpi;
652 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800653 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Andy McFadden91b2ca82014-06-13 14:04:23 -0700654 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655
Andy McFadden91b2ca82014-06-13 14:04:23 -0700656 // This is how far in advance a buffer must be queued for
657 // presentation at a given time. If you want a buffer to appear
658 // on the screen at time N, you must submit the buffer before
659 // (N - presentationDeadline).
660 //
661 // Normally it's one full refresh period (to give SF a chance to
662 // latch the buffer), but this can be reduced by configuring a
663 // DispSync offset. Any additional delays introduced by the hardware
664 // composer or panel must be accounted for here.
665 //
666 // We add an additional 1ms to allow for processing time and
667 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668 info.presentationDeadline = hwConfig->getVsyncPeriod() -
669 SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700670
671 // All non-virtual displays are currently considered secure.
672 info.secure = true;
673
Michael Wright28f24d02016-07-12 13:30:53 -0700674 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700675 }
676
Dan Stoza7f7da322014-05-02 15:26:25 -0700677 return NO_ERROR;
678}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700679
Andreas Gampe89fd4f72014-11-13 14:18:56 -0800680status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700681 DisplayStatInfo* stats) {
682 if (stats == NULL) {
683 return BAD_VALUE;
684 }
685
686 // FIXME for now we always return stats for the primary display
687 memset(stats, 0, sizeof(*stats));
688 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
689 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
690 return NO_ERROR;
691}
692
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700693int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
Dan Stoza24a42e92015-03-09 10:04:11 -0700694 sp<DisplayDevice> device(getDisplayDevice(display));
695 if (device != NULL) {
696 return device->getActiveConfig();
697 }
698 return BAD_VALUE;
Dan Stoza7f7da322014-05-02 15:26:25 -0700699}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700700
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700701void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
702 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
703 this);
704 int32_t type = hw->getDisplayType();
705 int currentMode = hw->getActiveConfig();
706
707 if (mode == currentMode) {
708 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
709 return;
710 }
711
712 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
713 ALOGW("Trying to set config for virtual display");
714 return;
715 }
716
717 hw->setActiveConfig(mode);
718 getHwComposer().setActiveConfig(type, mode);
719}
720
721status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
722 class MessageSetActiveConfig: public MessageBase {
723 SurfaceFlinger& mFlinger;
724 sp<IBinder> mDisplay;
725 int mMode;
726 public:
727 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
728 int mode) :
729 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
730 virtual bool handler() {
Michael Lentine7306c672014-07-30 13:00:37 -0700731 Vector<DisplayInfo> configs;
732 mFlinger.getDisplayConfigs(mDisplay, &configs);
Jesse Hall78442112014-08-07 22:43:06 -0700733 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
Michael Lentine9ae79d82014-07-30 16:42:12 -0700734 ALOGE("Attempt to set active config = %d for display with %zu configs",
Michael Lentine7306c672014-07-30 13:00:37 -0700735 mMode, configs.size());
Michael Wright28f24d02016-07-12 13:30:53 -0700736 return true;
Michael Lentine7306c672014-07-30 13:00:37 -0700737 }
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700738 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
739 if (hw == NULL) {
740 ALOGE("Attempt to set active config = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -0700741 mMode, mDisplay.get());
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700742 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
743 ALOGW("Attempt to set active config = %d for virtual display",
744 mMode);
745 } else {
746 mFlinger.setActiveConfigInternal(hw, mMode);
747 }
748 return true;
749 }
750 };
751 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
752 postMessageSync(msg);
Mathias Agopian888c8222012-08-04 21:10:38 -0700753 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700754}
Michael Wright28f24d02016-07-12 13:30:53 -0700755status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
756 Vector<android_color_mode_t>* outColorModes) {
757 if ((outColorModes == nullptr) || (display.get() == nullptr)) {
758 return BAD_VALUE;
759 }
760
761 if (!display.get()) {
762 return NAME_NOT_FOUND;
763 }
764
765 int32_t type = NAME_NOT_FOUND;
766 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
767 if (display == mBuiltinDisplays[i]) {
768 type = i;
769 break;
770 }
771 }
772
773 if (type < 0) {
774 return type;
775 }
776
777 std::vector<android_color_mode_t> modes = getHwComposer().getColorModes(type);
778 outColorModes->clear();
779 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
780
781 return NO_ERROR;
782}
783
784android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
785 sp<DisplayDevice> device(getDisplayDevice(display));
786 if (device != nullptr) {
787 return device->getActiveColorMode();
788 }
789 return static_cast<android_color_mode_t>(BAD_VALUE);
790}
791
792void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& hw,
793 android_color_mode_t mode) {
794 ALOGD("Set active color mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
795 this);
796 int32_t type = hw->getDisplayType();
797 android_color_mode_t currentMode = hw->getActiveColorMode();
798
799 if (mode == currentMode) {
800 ALOGD("Screen type=%d is already in color mode=%d", hw->getDisplayType(), mode);
801 return;
802 }
803
804 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
805 ALOGW("Trying to set config for virtual display");
806 return;
807 }
808
809 hw->setActiveColorMode(mode);
810 getHwComposer().setActiveColorMode(type, mode);
811}
812
813
814status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
815 android_color_mode_t colorMode) {
816 class MessageSetActiveColorMode: public MessageBase {
817 SurfaceFlinger& mFlinger;
818 sp<IBinder> mDisplay;
819 android_color_mode_t mMode;
820 public:
821 MessageSetActiveColorMode(SurfaceFlinger& flinger, const sp<IBinder>& disp,
822 android_color_mode_t mode) :
823 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
824 virtual bool handler() {
825 Vector<android_color_mode_t> modes;
826 mFlinger.getDisplayColorModes(mDisplay, &modes);
827 bool exists = std::find(std::begin(modes), std::end(modes), mMode) != std::end(modes);
828 if (mMode < 0 || !exists) {
829 ALOGE("Attempt to set invalid active color mode = %d for display %p", mMode,
830 mDisplay.get());
831 return true;
832 }
833 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
834 if (hw == nullptr) {
835 ALOGE("Attempt to set active color mode = %d for null display %p",
836 mMode, mDisplay.get());
837 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
838 ALOGW("Attempt to set active color mode= %d for virtual display",
839 mMode);
840 } else {
841 mFlinger.setActiveColorModeInternal(hw, mMode);
842 }
843 return true;
844 }
845 };
846 sp<MessageBase> msg = new MessageSetActiveColorMode(*this, display, colorMode);
847 postMessageSync(msg);
848 return NO_ERROR;
849}
Mathias Agopianc666cae2012-07-25 18:56:13 -0700850
Svetoslavd85084b2014-03-20 10:28:31 -0700851status_t SurfaceFlinger::clearAnimationFrameStats() {
852 Mutex::Autolock _l(mStateLock);
853 mAnimFrameTracker.clearStats();
854 return NO_ERROR;
855}
856
857status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
858 Mutex::Autolock _l(mStateLock);
859 mAnimFrameTracker.getStats(outStats);
860 return NO_ERROR;
861}
862
Dan Stozac4f471e2016-03-24 09:31:08 -0700863status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& display,
864 HdrCapabilities* outCapabilities) const {
865 Mutex::Autolock _l(mStateLock);
866
867 sp<const DisplayDevice> displayDevice(getDisplayDevice(display));
868 if (displayDevice == nullptr) {
869 ALOGE("getHdrCapabilities: Invalid display %p", displayDevice.get());
870 return BAD_VALUE;
871 }
872
873 std::unique_ptr<HdrCapabilities> capabilities =
874 mHwc->getHdrCapabilities(displayDevice->getHwcDisplayId());
875 if (capabilities) {
876 std::swap(*outCapabilities, *capabilities);
877 } else {
878 return BAD_VALUE;
879 }
880
881 return NO_ERROR;
882}
883
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700884status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
885 if (enable == mInjectVSyncs) {
886 return NO_ERROR;
887 }
888
889 if (enable) {
890 mInjectVSyncs = enable;
891 ALOGV("VSync Injections enabled");
892 if (mVSyncInjector.get() == nullptr) {
893 mVSyncInjector = new InjectVSyncSource();
894 mInjectorEventThread = new EventThread(mVSyncInjector, *this);
895 }
896 mEventQueue.setEventThread(mInjectorEventThread);
897 } else {
898 mInjectVSyncs = enable;
899 ALOGV("VSync Injections disabled");
900 mEventQueue.setEventThread(mSFEventThread);
901 mVSyncInjector.clear();
902 }
903 return NO_ERROR;
904}
905
906status_t SurfaceFlinger::injectVSync(nsecs_t when) {
907 if (!mInjectVSyncs) {
908 ALOGE("VSync Injections not enabled");
909 return BAD_VALUE;
910 }
911 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
912 ALOGV("Injecting VSync inside SurfaceFlinger");
913 mVSyncInjector->onInjectSyncEvent(when);
914 }
915 return NO_ERROR;
916}
917
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800918// ----------------------------------------------------------------------------
919
920sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
Mathias Agopian8aedd472012-01-24 16:39:14 -0800921 return mEventThread->createEventConnection();
Mathias Agopianbb641242010-05-18 17:06:55 -0700922}
923
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800924// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800925
926void SurfaceFlinger::waitForEvent() {
927 mEventQueue.waitMessage();
928}
929
930void SurfaceFlinger::signalTransaction() {
931 mEventQueue.invalidate();
932}
933
934void SurfaceFlinger::signalLayerUpdate() {
935 mEventQueue.invalidate();
936}
937
938void SurfaceFlinger::signalRefresh() {
939 mEventQueue.refresh();
940}
941
942status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800943 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800944 return mEventQueue.postMessage(msg, reltime);
945}
946
947status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -0800948 nsecs_t reltime, uint32_t /* flags */) {
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800949 status_t res = mEventQueue.postMessage(msg, reltime);
950 if (res == NO_ERROR) {
951 msg->wait();
952 }
953 return res;
954}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800955
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700956void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -0700957 do {
958 waitForEvent();
959 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800960}
961
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700962void SurfaceFlinger::enableHardwareVsync() {
963 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -0700964 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700965 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700966 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
967 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700968 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -0700969 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700970}
971
Jesse Hall948fe0c2013-10-14 12:56:09 -0700972void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700973 Mutex::Autolock _l(mHWVsyncLock);
974
Jesse Hall948fe0c2013-10-14 12:56:09 -0700975 if (makeAvailable) {
976 mHWVsyncAvailable = true;
977 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700978 // Hardware vsync is not currently available, so abort the resync
979 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -0700980 return;
981 }
982
Dan Stoza9e56aa02015-11-02 13:00:03 -0800983 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
984 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700985
986 mPrimaryDispSync.reset();
987 mPrimaryDispSync.setPeriod(period);
988
989 if (!mPrimaryHWVsyncEnabled) {
990 mPrimaryDispSync.beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -0700991 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
992 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700993 mPrimaryHWVsyncEnabled = true;
994 }
995}
996
Jesse Hall948fe0c2013-10-14 12:56:09 -0700997void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700998 Mutex::Autolock _l(mHWVsyncLock);
999 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001000 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
1001 mEventControlThread->setVsyncEnabled(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001002 mPrimaryDispSync.endResync();
1003 mPrimaryHWVsyncEnabled = false;
1004 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001005 if (makeUnavailable) {
1006 mHWVsyncAvailable = false;
1007 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001008}
1009
Tim Murray4a4e4a22016-04-19 16:29:23 +00001010void SurfaceFlinger::resyncWithRateLimit() {
1011 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
1012 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001013 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001014 }
1015}
1016
Dan Stoza9e56aa02015-11-02 13:00:03 -08001017void SurfaceFlinger::onVSyncReceived(int32_t type, nsecs_t timestamp) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001018 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001019
Jamie Gennisd1700752013-10-14 12:22:52 -07001020 { // Scope for the lock
1021 Mutex::Autolock _l(mHWVsyncLock);
1022 if (type == 0 && mPrimaryHWVsyncEnabled) {
1023 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001024 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001025 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001026
1027 if (needsHwVsync) {
1028 enableHardwareVsync();
1029 } else {
1030 disableHardwareVsync(false);
1031 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001032}
1033
Dan Stoza9e56aa02015-11-02 13:00:03 -08001034void SurfaceFlinger::onHotplugReceived(int32_t disp, bool connected) {
1035 ALOGV("onHotplugReceived(%d, %s)", disp, connected ? "true" : "false");
1036 if (disp == DisplayDevice::DISPLAY_PRIMARY) {
1037 Mutex::Autolock lock(mStateLock);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001038
Dan Stoza9e56aa02015-11-02 13:00:03 -08001039 // All non-virtual displays are currently considered secure.
1040 bool isSecure = true;
1041
1042 int32_t type = DisplayDevice::DISPLAY_PRIMARY;
1043 createBuiltinDisplayLocked(DisplayDevice::DISPLAY_PRIMARY);
1044 wp<IBinder> token = mBuiltinDisplays[type];
1045
1046 sp<IGraphicBufferProducer> producer;
1047 sp<IGraphicBufferConsumer> consumer;
1048 BufferQueue::createBufferQueue(&producer, &consumer,
1049 new GraphicBufferAlloc());
1050
1051 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc,
1052 DisplayDevice::DISPLAY_PRIMARY, consumer);
1053 sp<DisplayDevice> hw = new DisplayDevice(this,
1054 DisplayDevice::DISPLAY_PRIMARY, disp, isSecure, token, fbs,
1055 producer, mRenderEngine->getEGLConfig());
1056 mDisplays.add(token, hw);
1057 } else {
1058 auto type = DisplayDevice::DISPLAY_EXTERNAL;
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001059 Mutex::Autolock _l(mStateLock);
Jesse Hall692c7232012-11-08 15:41:56 -08001060 if (connected) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001061 createBuiltinDisplayLocked(type);
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001062 } else {
Jesse Hall692c7232012-11-08 15:41:56 -08001063 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
1064 mBuiltinDisplays[type].clear();
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001065 }
1066 setTransactionFlags(eDisplayTransactionNeeded);
1067
Andy McFadden9e9689c2012-10-10 18:17:51 -07001068 // Defer EventThread notification until SF has updated mDisplays.
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001069 }
Mathias Agopian86303202012-07-24 22:46:10 -07001070}
1071
Dan Stoza9e56aa02015-11-02 13:00:03 -08001072void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001073 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001074 getHwComposer().setVsyncEnabled(disp,
1075 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001076}
1077
Mathias Agopian4fec8732012-06-29 14:12:52 -07001078void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001079 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001080 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001081 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001082 bool frameMissed = !mHadClientComposition &&
1083 mPreviousPresentFence != Fence::NO_FENCE &&
1084 mPreviousPresentFence->getSignalTime() == INT64_MAX;
1085 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Dan Stozac5da2712016-07-20 15:38:12 -07001086 if (mPropagateBackpressure && frameMissed) {
Dan Stoza50182882016-07-08 12:02:20 -07001087 signalLayerUpdate();
1088 break;
1089 }
1090
Dan Stoza6b9454d2014-11-07 16:00:59 -08001091 bool refreshNeeded = handleMessageTransaction();
1092 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001093 refreshNeeded |= mRepaintEverything;
Dan Stoza6b9454d2014-11-07 16:00:59 -08001094 if (refreshNeeded) {
Dan Stoza58784442014-12-02 16:58:17 -08001095 // Signal a refresh if a transaction modified the window state,
1096 // a new buffer was latched, or if HWC has requested a full
1097 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001098 signalRefresh();
1099 }
1100 break;
1101 }
1102 case MessageQueue::REFRESH: {
1103 handleMessageRefresh();
1104 break;
1105 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001106 }
1107}
1108
Dan Stoza6b9454d2014-11-07 16:00:59 -08001109bool SurfaceFlinger::handleMessageTransaction() {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001110 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001111 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001112 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001113 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001114 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001115 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001116}
1117
Dan Stoza6b9454d2014-11-07 16:00:59 -08001118bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001119 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001120 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001121}
1122
1123void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001124 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001125
Pablo Ceballos40845df2016-01-25 17:41:15 -08001126 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001127
Dan Stoza05dacfb2016-07-01 13:33:38 -07001128 preComposition();
1129 rebuildLayerStacks();
1130 setUpHWComposer();
1131 doDebugFlashRegions();
1132 doComposition();
1133 postComposition(refreshStartTime);
1134
1135 mPreviousPresentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Dan Stozabfbffeb2016-07-21 14:49:33 -07001136
1137 mHadClientComposition = false;
1138 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1139 const sp<DisplayDevice>& displayDevice = mDisplays[displayId];
1140 mHadClientComposition = mHadClientComposition ||
1141 mHwc->hasClientComposition(displayDevice->getHwcDisplayId());
1142 }
Dan Stoza14cd37c2015-07-09 12:43:33 -07001143
Dan Stoza9e56aa02015-11-02 13:00:03 -08001144 // Release any buffers which were replaced this frame
1145 for (auto& layer : mLayersWithQueuedFrames) {
1146 layer->releasePendingBuffer();
1147 }
1148 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001149}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001150
Mathias Agopiancd60f992012-08-16 16:28:27 -07001151void SurfaceFlinger::doDebugFlashRegions()
1152{
1153 // is debugging enabled
1154 if (CC_LIKELY(!mDebugRegion))
1155 return;
1156
1157 const bool repaintEverything = mRepaintEverything;
1158 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1159 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001160 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001161 // transform the dirty region into this screen's coordinate space
1162 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1163 if (!dirtyRegion.isEmpty()) {
1164 // redraw the whole screen
1165 doComposeSurfaces(hw, Region(hw->bounds()));
1166
1167 // and draw the dirty region
Mathias Agopiancd60f992012-08-16 16:28:27 -07001168 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07001169 RenderEngine& engine(getRenderEngine());
1170 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1171
Mathias Agopianda27af92012-09-13 18:17:13 -07001172 hw->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001173 }
1174 }
1175 }
1176
1177 postFramebuffer();
1178
1179 if (mDebugRegion > 1) {
1180 usleep(mDebugRegion * 1000);
1181 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001182
Dan Stoza9e56aa02015-11-02 13:00:03 -08001183 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001184 auto& displayDevice = mDisplays[displayId];
1185 if (!displayDevice->isDisplayOn()) {
1186 continue;
1187 }
1188
1189 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001190 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1191 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001192 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001193}
1194
1195void SurfaceFlinger::preComposition()
1196{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001197 ATRACE_CALL();
1198 ALOGV("preComposition");
1199
Mathias Agopiancd60f992012-08-16 16:28:27 -07001200 bool needExtraInvalidate = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001201 const LayerVector& layers(mDrawingState.layersSortedByZ);
1202 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001203 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001204 if (layers[i]->onPreComposition()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001205 needExtraInvalidate = true;
1206 }
1207 }
1208 if (needExtraInvalidate) {
1209 signalLayerUpdate();
1210 }
1211}
1212
Pablo Ceballos40845df2016-01-25 17:41:15 -08001213void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001214{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001215 ATRACE_CALL();
1216 ALOGV("postComposition");
1217
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001218 const LayerVector& layers(mDrawingState.layersSortedByZ);
1219 const size_t count = layers.size();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001220 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001221 bool frameLatched = layers[i]->onPostComposition();
1222 if (frameLatched) {
1223 recordBufferingStats(layers[i]->getName().string(),
1224 layers[i]->getOccupancyHistory(false));
1225 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001226 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001227
Dan Stoza9e56aa02015-11-02 13:00:03 -08001228 sp<Fence> presentFence = mHwc->getRetireFence(HWC_DISPLAY_PRIMARY);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001229
1230 if (presentFence->isValid()) {
1231 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1232 enableHardwareVsync();
1233 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001234 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001235 }
1236 }
1237
Dan Stozab90cf072015-03-05 11:05:59 -08001238 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Andy McFadden5167ec62014-05-22 13:08:43 -07001239 if (kIgnorePresentFences) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001240 if (hw->isDisplayOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001241 enableHardwareVsync();
1242 }
1243 }
1244
Pablo Ceballos40845df2016-01-25 17:41:15 -08001245 mFenceTracker.addFrame(refreshStartTime, presentFence,
1246 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1247
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001248 if (mAnimCompositionPending) {
1249 mAnimCompositionPending = false;
1250
Jesse Halla9a1b002013-02-27 16:39:25 -08001251 if (presentFence->isValid()) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001252 mAnimFrameTracker.setActualPresentFence(presentFence);
1253 } else {
1254 // The HWC doesn't support present fences, so use the refresh
1255 // timestamp instead.
Dan Stoza9e56aa02015-11-02 13:00:03 -08001256 nsecs_t presentTime =
1257 mHwc->getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001258 mAnimFrameTracker.setActualPresentTime(presentTime);
1259 }
1260 mAnimFrameTracker.advanceFrame();
1261 }
Dan Stozab90cf072015-03-05 11:05:59 -08001262
1263 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1264 return;
1265 }
1266
1267 nsecs_t currentTime = systemTime();
1268 if (mHasPoweredOff) {
1269 mHasPoweredOff = false;
1270 } else {
1271 nsecs_t period = mPrimaryDispSync.getPeriod();
1272 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1273 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1274 if (numPeriods < NUM_BUCKETS - 1) {
1275 mFrameBuckets[numPeriods] += elapsedTime;
1276 } else {
1277 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1278 }
1279 mTotalTime += elapsedTime;
1280 }
1281 mLastSwapTime = currentTime;
Mathias Agopiancd60f992012-08-16 16:28:27 -07001282}
1283
1284void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001285 ATRACE_CALL();
1286 ALOGV("rebuildLayerStacks");
1287
Mathias Agopiancd60f992012-08-16 16:28:27 -07001288 // rebuild the visible layer list per screen
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001289 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001290 ATRACE_CALL();
Mathias Agopian87baae12012-07-31 12:38:26 -07001291 mVisibleRegionsDirty = false;
1292 invalidateHwcGeometry();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001293
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001294 const LayerVector& layers(mDrawingState.layersSortedByZ);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001295 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001296 Region opaqueRegion;
1297 Region dirtyRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08001298 Vector<sp<Layer>> layersSortedByZ;
1299 const sp<DisplayDevice>& displayDevice(mDisplays[dpy]);
1300 const Transform& tr(displayDevice->getTransform());
1301 const Rect bounds(displayDevice->getBounds());
1302 if (displayDevice->isDisplayOn()) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001303 SurfaceFlinger::computeVisibleRegions(layers,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001304 displayDevice->getLayerStack(), dirtyRegion,
1305 opaqueRegion);
Mathias Agopian7e7ed7f2012-08-28 14:20:00 -07001306
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001307 const size_t count = layers.size();
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001308 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001309 const sp<Layer>& layer(layers[i]);
1310 const Layer::State& s(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001311 if (s.layerStack == displayDevice->getLayerStack()) {
Jesse Halla8026d22012-09-25 13:25:04 -07001312 Region drawRegion(tr.transform(
1313 layer->visibleNonTransparentRegion));
1314 drawRegion.andSelf(bounds);
1315 if (!drawRegion.isEmpty()) {
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001316 layersSortedByZ.add(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 } else {
1318 // Clear out the HWC layer if this layer was
1319 // previously visible, but no longer is
1320 layer->setHwcLayer(displayDevice->getHwcDisplayId(),
1321 nullptr);
Mathias Agopiance3a0a52012-09-12 15:34:57 -07001322 }
Mathias Agopian87baae12012-07-31 12:38:26 -07001323 }
1324 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001325 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001326 displayDevice->setVisibleLayersSortedByZ(layersSortedByZ);
1327 displayDevice->undefinedRegion.set(bounds);
1328 displayDevice->undefinedRegion.subtractSelf(
1329 tr.transform(opaqueRegion));
1330 displayDevice->dirtyRegion.orSelf(dirtyRegion);
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001331 }
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001332 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001333}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001334
Mathias Agopiancd60f992012-08-16 16:28:27 -07001335void SurfaceFlinger::setUpHWComposer() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001336 ATRACE_CALL();
1337 ALOGV("setUpHWComposer");
1338
Jesse Hall028dc8f2013-08-20 16:35:32 -07001339 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Jesse Hallb7a05492014-08-14 15:45:06 -07001340 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1341 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1342 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1343
1344 // If nothing has changed (!dirty), don't recompose.
1345 // If something changed, but we don't currently have any visible layers,
1346 // and didn't when we last did a composition, then skip it this time.
1347 // The second rule does two things:
1348 // - When all layers are removed from a display, we'll emit one black
1349 // frame, then nothing more until we get new layers.
1350 // - When a display is created with a private layer stack, we won't
1351 // emit any black frames until a layer is added to the layer stack.
1352 bool mustRecompose = dirty && !(empty && wasEmpty);
1353
1354 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1355 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1356 mustRecompose ? "doing" : "skipping",
1357 dirty ? "+" : "-",
1358 empty ? "+" : "-",
1359 wasEmpty ? "+" : "-");
1360
Dan Stoza71433162014-02-04 16:22:36 -08001361 mDisplays[dpy]->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07001362
1363 if (mustRecompose) {
1364 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1365 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07001366 }
1367
Dan Stoza9e56aa02015-11-02 13:00:03 -08001368 // build the h/w work list
1369 if (CC_UNLIKELY(mGeometryInvalid)) {
1370 mGeometryInvalid = false;
1371 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1372 sp<const DisplayDevice> displayDevice(mDisplays[dpy]);
1373 const auto hwcId = displayDevice->getHwcDisplayId();
1374 if (hwcId >= 0) {
1375 const Vector<sp<Layer>>& currentLayers(
1376 displayDevice->getVisibleLayersSortedByZ());
1377 bool foundLayerWithoutHwc = false;
1378 for (auto& layer : currentLayers) {
1379 if (!layer->hasHwcLayer(hwcId)) {
1380 auto hwcLayer = mHwc->createLayer(hwcId);
1381 if (hwcLayer) {
1382 layer->setHwcLayer(hwcId, std::move(hwcLayer));
1383 } else {
1384 layer->forceClientComposition(hwcId);
1385 foundLayerWithoutHwc = true;
1386 continue;
Jamie Gennisa4310c82012-09-25 20:26:00 -07001387 }
1388 }
Jamie Gennisa4310c82012-09-25 20:26:00 -07001389
Dan Stoza9e56aa02015-11-02 13:00:03 -08001390 layer->setGeometry(displayDevice);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001391 if (mDebugDisableHWC || mDebugRegion) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001392 layer->forceClientComposition(hwcId);
Riley Andrews03414a12014-07-01 14:22:59 -07001393 }
1394 }
1395 }
1396 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001397 }
Riley Andrews03414a12014-07-01 14:22:59 -07001398
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001399
1400 mat4 colorMatrix = mColorMatrix * mDaltonizer();
1401
Dan Stoza9e56aa02015-11-02 13:00:03 -08001402 // Set the per-frame data
1403 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1404 auto& displayDevice = mDisplays[displayId];
1405 const auto hwcId = displayDevice->getHwcDisplayId();
1406 if (hwcId < 0) {
1407 continue;
Jesse Hall38efe862013-04-06 23:12:29 -07001408 }
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001409 if (colorMatrix != mPreviousColorMatrix) {
1410 status_t result = mHwc->setColorTransform(hwcId, colorMatrix);
1411 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on "
1412 "display %zd: %d", displayId, result);
1413 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001414 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1415 layer->setPerFrameData(displayDevice);
1416 }
1417 }
1418
Dan Stoza9f26a9c2016-06-22 14:51:09 -07001419 mPreviousColorMatrix = colorMatrix;
1420
Dan Stoza9e56aa02015-11-02 13:00:03 -08001421 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001422 auto& displayDevice = mDisplays[displayId];
1423 if (!displayDevice->isDisplayOn()) {
1424 continue;
1425 }
1426
1427 status_t result = displayDevice->prepareFrame(*mHwc);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001428 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %zd failed:"
1429 " %d (%s)", displayId, result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001430 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001431}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001432
Mathias Agopiancd60f992012-08-16 16:28:27 -07001433void SurfaceFlinger::doComposition() {
1434 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001435 ALOGV("doComposition");
1436
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001437 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001438 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001439 const sp<DisplayDevice>& hw(mDisplays[dpy]);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07001440 if (hw->isDisplayOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001441 // transform the dirty region into this screen's coordinate space
1442 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08001443
1444 // repaint the framebuffer (if needed)
1445 doDisplayComposition(hw, dirtyRegion);
1446
Mathias Agopiancd60f992012-08-16 16:28:27 -07001447 hw->dirtyRegion.clear();
1448 hw->flip(hw->swapRegion);
1449 hw->swapRegion.clear();
Mathias Agopian87baae12012-07-31 12:38:26 -07001450 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001451 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001452 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001453}
1454
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001455void SurfaceFlinger::postFramebuffer()
1456{
Mathias Agopian841cde52012-03-01 15:44:37 -08001457 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001458 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08001459
Mathias Agopiana44b0412011-10-16 18:46:35 -07001460 const nsecs_t now = systemTime();
1461 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07001462
Dan Stoza9e56aa02015-11-02 13:00:03 -08001463 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1464 auto& displayDevice = mDisplays[displayId];
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001465 if (!displayDevice->isDisplayOn()) {
1466 continue;
1467 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001468 const auto hwcId = displayDevice->getHwcDisplayId();
1469 if (hwcId >= 0) {
1470 mHwc->commit(hwcId);
Mathias Agopian2a231842012-09-24 18:12:35 -07001471 }
Dan Stoza2dc3be82016-04-06 14:05:37 -07001472 displayDevice->onSwapBuffersCompleted();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001473 if (displayId == 0) {
1474 // Make the default display current because the VirtualDisplayDevice
1475 // code cannot deal with dequeueBuffer() being called outside of the
1476 // composition loop; however the code below can call glFlush() which
1477 // is allowed to (and does in some case) call dequeueBuffer().
1478 displayDevice->makeCurrent(mEGLDisplay, mEGLContext);
1479 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001480 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1481 sp<Fence> releaseFence = Fence::NO_FENCE;
1482 if (layer->getCompositionType(hwcId) == HWC2::Composition::Client) {
1483 releaseFence = displayDevice->getClientTargetAcquireFence();
1484 } else {
1485 auto hwcLayer = layer->getHwcLayer(hwcId);
1486 releaseFence = mHwc->getLayerReleaseFence(hwcId, hwcLayer);
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07001487 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001488 layer->onLayerDisplayed(releaseFence);
1489 }
1490 if (hwcId >= 0) {
1491 mHwc->clearReleaseFences(hwcId);
Jesse Hallef194142012-06-14 14:45:17 -07001492 }
Jamie Gennise8696a42012-01-15 18:54:57 -08001493 }
1494
Mathias Agopiana44b0412011-10-16 18:46:35 -07001495 mLastSwapBufferTime = systemTime() - now;
1496 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07001497
1498 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1499 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1500 logFrameStats();
1501 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001502}
1503
Mathias Agopian87baae12012-07-31 12:38:26 -07001504void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001505{
Mathias Agopian841cde52012-03-01 15:44:37 -08001506 ATRACE_CALL();
1507
Mathias Agopian7cc6df52013-06-05 14:30:54 -07001508 // here we keep a copy of the drawing state (that is the state that's
1509 // going to be overwritten by handleTransactionLocked()) outside of
1510 // mStateLock so that the side-effects of the State assignment
1511 // don't happen with mStateLock held (which can cause deadlocks).
1512 State drawingState(mDrawingState);
1513
Mathias Agopianca4d3602011-05-19 15:38:14 -07001514 Mutex::Autolock _l(mStateLock);
1515 const nsecs_t now = systemTime();
1516 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001517
Mathias Agopianca4d3602011-05-19 15:38:14 -07001518 // Here we're guaranteed that some transaction flags are set
1519 // so we can call handleTransactionLocked() unconditionally.
1520 // We call getTransactionFlags(), which will also clear the flags,
1521 // with mStateLock held to guarantee that mCurrentState won't change
1522 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07001523
Mathias Agopiane57f2922012-08-09 16:29:12 -07001524 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07001525 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07001526
Mathias Agopianca4d3602011-05-19 15:38:14 -07001527 mLastTransactionTime = systemTime() - now;
1528 mDebugInTransaction = 0;
1529 invalidateHwcGeometry();
1530 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07001531}
1532
Mathias Agopian87baae12012-07-31 12:38:26 -07001533void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07001534{
1535 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001536 const size_t count = currentLayers.size();
1537
Dan Stoza7dde5992015-05-22 09:51:44 -07001538 // Notify all layers of available frames
1539 for (size_t i = 0; i < count; ++i) {
1540 currentLayers[i]->notifyAvailableFrames();
1541 }
1542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001543 /*
1544 * Traversal of the children
1545 * (perform the transaction for each of them if needed)
1546 */
1547
Mathias Agopian3559b072012-08-15 13:46:03 -07001548 if (transactionFlags & eTraversalNeeded) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001549 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001550 const sp<Layer>& layer(currentLayers[i]);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001551 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1552 if (!trFlags) continue;
1553
1554 const uint32_t flags = layer->doTransaction(0);
1555 if (flags & Layer::eVisibleRegion)
1556 mVisibleRegionsDirty = true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001557 }
1558 }
1559
1560 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07001561 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001562 */
1563
Mathias Agopiane57f2922012-08-09 16:29:12 -07001564 if (transactionFlags & eDisplayTransactionNeeded) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001565 // here we take advantage of Vector's copy-on-write semantics to
1566 // improve performance by skipping the transaction entirely when
1567 // know that the lists are identical
Mathias Agopiane57f2922012-08-09 16:29:12 -07001568 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1569 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
Mathias Agopian92a979a2012-08-02 18:32:23 -07001570 if (!curr.isIdenticalTo(draw)) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001571 mVisibleRegionsDirty = true;
Mathias Agopian92a979a2012-08-02 18:32:23 -07001572 const size_t cc = curr.size();
Mathias Agopian93997a82012-08-29 17:30:36 -07001573 size_t dc = draw.size();
Mathias Agopian92a979a2012-08-02 18:32:23 -07001574
1575 // find the displays that were removed
1576 // (ie: in drawing state but not in current state)
1577 // also handle displays that changed
1578 // (ie: displays that are in both lists)
1579 for (size_t i=0 ; i<dc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001580 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1581 if (j < 0) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001582 // in drawing state but not in current state
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001583 if (!draw[i].isMainDisplay()) {
Andy McFadden27ec5732012-10-02 19:04:45 -07001584 // Call makeCurrent() on the primary display so we can
1585 // be sure that nothing associated with this display
1586 // is current.
Jesse Hall02d86562013-03-25 14:43:23 -07001587 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
Mathias Agopian875d8e12013-06-07 15:35:48 -07001588 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
Jesse Hall02d86562013-03-25 14:43:23 -07001589 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1590 if (hw != NULL)
1591 hw->disconnect(getHwComposer());
Jesse Hall9e663de2013-08-16 14:28:37 -07001592 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
Jesse Hall7adb0f82013-03-06 16:13:49 -08001593 mEventThread->onHotplugReceived(draw[i].type, false);
Jesse Hall02d86562013-03-25 14:43:23 -07001594 mDisplays.removeItem(draw.keyAt(i));
Mathias Agopian92a979a2012-08-02 18:32:23 -07001595 } else {
1596 ALOGW("trying to remove the main display");
1597 }
1598 } else {
1599 // this display is in both lists. see if something changed.
Mathias Agopiane57f2922012-08-09 16:29:12 -07001600 const DisplayDeviceState& state(curr[j]);
Mathias Agopian3ee454a2012-08-27 16:28:24 -07001601 const wp<IBinder>& display(curr.keyAt(j));
Marco Nelissen097ca272014-11-14 08:01:01 -08001602 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1603 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
Dan Albert1474f882014-09-08 18:59:09 -07001604 if (state_binder != draw_binder) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001605 // changing the surface is like destroying and
Mathias Agopian93997a82012-08-29 17:30:36 -07001606 // recreating the DisplayDevice, so we just remove it
1607 // from the drawing state, so that it get re-added
1608 // below.
Jesse Hall02d86562013-03-25 14:43:23 -07001609 sp<DisplayDevice> hw(getDisplayDevice(display));
1610 if (hw != NULL)
1611 hw->disconnect(getHwComposer());
Mathias Agopian93997a82012-08-29 17:30:36 -07001612 mDisplays.removeItem(display);
1613 mDrawingState.displays.removeItemsAt(i);
1614 dc--; i--;
1615 // at this point we must loop to the next item
1616 continue;
1617 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07001618
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07001619 const sp<DisplayDevice> disp(getDisplayDevice(display));
Mathias Agopian93997a82012-08-29 17:30:36 -07001620 if (disp != NULL) {
1621 if (state.layerStack != draw[i].layerStack) {
1622 disp->setLayerStack(state.layerStack);
1623 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07001624 if ((state.orientation != draw[i].orientation)
1625 || (state.viewport != draw[i].viewport)
1626 || (state.frame != draw[i].frame))
1627 {
1628 disp->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001629 state.viewport, state.frame);
Mathias Agopian93997a82012-08-29 17:30:36 -07001630 }
Michael Lentine47e45402014-07-18 15:34:25 -07001631 if (state.width != draw[i].width || state.height != draw[i].height) {
1632 disp->setDisplaySize(state.width, state.height);
1633 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001634 }
1635 }
1636 }
1637
1638 // find displays that were added
1639 // (ie: in current state but not in drawing state)
1640 for (size_t i=0 ; i<cc ; i++) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001641 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07001642 const DisplayDeviceState& state(curr[i]);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001643
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001644 sp<DisplaySurface> dispSurface;
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001645 sp<IGraphicBufferProducer> producer;
Dan Stozab9b08832014-03-13 11:55:57 -07001646 sp<IGraphicBufferProducer> bqProducer;
1647 sp<IGraphicBufferConsumer> bqConsumer;
Dan Stoza70982a52016-01-11 23:40:44 +00001648 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1649 new GraphicBufferAlloc());
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001650
Dan Stoza9e56aa02015-11-02 13:00:03 -08001651 int32_t hwcId = -1;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001652 if (state.isVirtualDisplay()) {
Jesse Hall02d86562013-03-25 14:43:23 -07001653 // Virtual displays without a surface are dormant:
1654 // they have external state (layer stack, projection,
1655 // etc.) but no internal state (i.e. a DisplayDevice).
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001656 if (state.surface != NULL) {
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001657
Dan Stoza1f3efb12014-10-15 16:34:55 -07001658 int width = 0;
1659 int status = state.surface->query(
1660 NATIVE_WINDOW_WIDTH, &width);
1661 ALOGE_IF(status != NO_ERROR,
1662 "Unable to query width (%d)", status);
1663 int height = 0;
1664 status = state.surface->query(
1665 NATIVE_WINDOW_HEIGHT, &height);
1666 ALOGE_IF(status != NO_ERROR,
1667 "Unable to query height (%d)", status);
Dan Stoza5cf424b2016-05-20 14:02:39 -07001668 int intFormat = 0;
1669 status = state.surface->query(
1670 NATIVE_WINDOW_FORMAT, &intFormat);
1671 ALOGE_IF(status != NO_ERROR,
1672 "Unable to query format (%d)", status);
1673 auto format = static_cast<android_pixel_format_t>(
1674 intFormat);
Dan Stoza1f3efb12014-10-15 16:34:55 -07001675
Dan Stoza5cf424b2016-05-20 14:02:39 -07001676 mHwc->allocateVirtualDisplay(width, height, &format,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001677 &hwcId);
1678
Dan Stoza5cf424b2016-05-20 14:02:39 -07001679 // TODO: Plumb requested format back up to consumer
1680
Dan Stoza9e56aa02015-11-02 13:00:03 -08001681 sp<VirtualDisplaySurface> vds =
1682 new VirtualDisplaySurface(*mHwc,
1683 hwcId, state.surface, bqProducer,
1684 bqConsumer, state.displayName);
Mathias Agopiandb89edc2013-08-02 01:40:18 -07001685
1686 dispSurface = vds;
Michael Lentine47e45402014-07-18 15:34:25 -07001687 producer = vds;
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001688 }
1689 } else {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001690 ALOGE_IF(state.surface!=NULL,
1691 "adding a supported display, but rendering "
1692 "surface is provided (%p), ignoring it",
1693 state.surface.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -08001694 if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
1695 hwcId = DisplayDevice::DISPLAY_EXTERNAL;
1696 dispSurface = new FramebufferSurface(*mHwc,
1697 DisplayDevice::DISPLAY_EXTERNAL,
1698 bqConsumer);
1699 producer = bqProducer;
1700 } else {
1701 ALOGE("Attempted to add non-external non-virtual"
1702 " display");
1703 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07001704 }
1705
1706 const wp<IBinder>& display(curr.keyAt(i));
Jesse Hall99c7dbb2013-03-14 14:29:29 -07001707 if (dispSurface != NULL) {
Mathias Agopiancde87a32012-09-13 14:09:01 -07001708 sp<DisplayDevice> hw = new DisplayDevice(this,
Dan Stoza9e56aa02015-11-02 13:00:03 -08001709 state.type, hwcId, state.isSecure, display,
1710 dispSurface, producer,
Jesse Hall05f8c702013-12-23 20:44:38 -08001711 mRenderEngine->getEGLConfig());
Mathias Agopiancde87a32012-09-13 14:09:01 -07001712 hw->setLayerStack(state.layerStack);
1713 hw->setProjection(state.orientation,
Jeff Brown4fb39992012-09-07 12:55:10 -07001714 state.viewport, state.frame);
Andy McFadden8dfa92f2012-09-17 18:27:17 -07001715 hw->setDisplayName(state.displayName);
Mathias Agopiancde87a32012-09-13 14:09:01 -07001716 mDisplays.add(display, hw);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001717 if (!state.isVirtualDisplay()) {
Jesse Hall7adb0f82013-03-06 16:13:49 -08001718 mEventThread->onHotplugReceived(state.type, true);
Jesse Hall1c569c42013-04-05 13:44:52 -07001719 }
Mathias Agopian93997a82012-08-29 17:30:36 -07001720 }
Mathias Agopian92a979a2012-08-02 18:32:23 -07001721 }
1722 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001723 }
Mathias Agopian3559b072012-08-15 13:46:03 -07001724 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001725
Mathias Agopian84300952012-11-21 16:02:13 -08001726 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1727 // The transform hint might have changed for some layers
1728 // (either because a display has changed, or because a layer
1729 // as changed).
1730 //
1731 // Walk through all the layers in currentLayers,
1732 // and update their transform hint.
1733 //
1734 // If a layer is visible only on a single display, then that
1735 // display is used to calculate the hint, otherwise we use the
1736 // default display.
1737 //
1738 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1739 // the hint is set before we acquire a buffer from the surface texture.
1740 //
1741 // NOTE: layer transactions have taken place already, so we use their
1742 // drawing state. However, SurfaceFlinger's own transaction has not
1743 // happened yet, so we must use the current state layer list
1744 // (soon to become the drawing state list).
1745 //
1746 sp<const DisplayDevice> disp;
1747 uint32_t currentlayerStack = 0;
1748 for (size_t i=0; i<count; i++) {
1749 // NOTE: we rely on the fact that layers are sorted by
1750 // layerStack first (so we don't have to traverse the list
1751 // of displays for every layer).
Mathias Agopian13127d82013-03-05 17:47:11 -08001752 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001753 uint32_t layerStack = layer->getDrawingState().layerStack;
Mathias Agopian84300952012-11-21 16:02:13 -08001754 if (i==0 || currentlayerStack != layerStack) {
1755 currentlayerStack = layerStack;
1756 // figure out if this layerstack is mirrored
1757 // (more than one display) if so, pick the default display,
1758 // if not, pick the only display it's on.
1759 disp.clear();
1760 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1761 sp<const DisplayDevice> hw(mDisplays[dpy]);
1762 if (hw->getLayerStack() == currentlayerStack) {
1763 if (disp == NULL) {
1764 disp = hw;
1765 } else {
Chet Haase91d25932013-04-11 15:24:55 -07001766 disp = NULL;
Mathias Agopian84300952012-11-21 16:02:13 -08001767 break;
1768 }
1769 }
1770 }
1771 }
Chet Haase91d25932013-04-11 15:24:55 -07001772 if (disp == NULL) {
1773 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1774 // redraw after transform hint changes. See bug 8508397.
1775
1776 // could be null when this layer is using a layerStack
1777 // that is not visible on any display. Also can occur at
1778 // screen off/on times.
1779 disp = getDefaultDisplayDevice();
Mathias Agopian84300952012-11-21 16:02:13 -08001780 }
Chet Haase91d25932013-04-11 15:24:55 -07001781 layer->updateTransformHint(disp);
Mathias Agopian84300952012-11-21 16:02:13 -08001782 }
1783 }
1784
1785
Mathias Agopian3559b072012-08-15 13:46:03 -07001786 /*
1787 * Perform our own transaction if needed
1788 */
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001789
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001790 const LayerVector& layers(mDrawingState.layersSortedByZ);
1791 if (currentLayers.size() > layers.size()) {
Mathias Agopian3559b072012-08-15 13:46:03 -07001792 // layers have been added
1793 mVisibleRegionsDirty = true;
1794 }
1795
1796 // some layers might have been removed, so
1797 // we need to update the regions they're exposing.
1798 if (mLayersRemoved) {
1799 mLayersRemoved = false;
1800 mVisibleRegionsDirty = true;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001801 const size_t count = layers.size();
Mathias Agopian3559b072012-08-15 13:46:03 -07001802 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001803 const sp<Layer>& layer(layers[i]);
Mathias Agopian3559b072012-08-15 13:46:03 -07001804 if (currentLayers.indexOf(layer) < 0) {
1805 // this layer is not visible anymore
1806 // TODO: we could traverse the tree from front to back and
1807 // compute the actual visible region
1808 // TODO: we could cache the transformed region
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001809 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001810 Region visibleReg = s.active.transform.transform(
Mathias Agopian1501d542012-09-04 21:04:09 -07001811 Region(Rect(s.active.w, s.active.h)));
1812 invalidateLayerStack(s.layerStack, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07001813 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001814 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001815 }
1816
1817 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07001818
1819 updateCursorAsync();
1820}
1821
1822void SurfaceFlinger::updateCursorAsync()
1823{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001824 for (size_t displayId = 0; displayId < mDisplays.size(); ++displayId) {
1825 auto& displayDevice = mDisplays[displayId];
1826 if (displayDevice->getHwcDisplayId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07001827 continue;
1828 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001829
1830 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
1831 layer->updateCursorPosition(displayDevice);
Riley Andrews03414a12014-07-01 14:22:59 -07001832 }
1833 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07001834}
1835
1836void SurfaceFlinger::commitTransaction()
1837{
1838 if (!mLayersPendingRemoval.isEmpty()) {
1839 // Notify removed layers now that they can't be drawn from
1840 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001841 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1842 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Mathias Agopian4fec8732012-06-29 14:12:52 -07001843 mLayersPendingRemoval[i]->onRemoved();
1844 }
1845 mLayersPendingRemoval.clear();
1846 }
1847
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001848 // If this transaction is part of a window animation then the next frame
1849 // we composite should be considered an animation as well.
1850 mAnimCompositionPending = mAnimTransactionPending;
1851
Mathias Agopian4fec8732012-06-29 14:12:52 -07001852 mDrawingState = mCurrentState;
Jamie Gennis2d5e2302012-10-15 18:24:43 -07001853 mTransactionPending = false;
1854 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001855 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001856}
1857
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001858void SurfaceFlinger::computeVisibleRegions(
Mathias Agopian87baae12012-07-31 12:38:26 -07001859 const LayerVector& currentLayers, uint32_t layerStack,
1860 Region& outDirtyRegion, Region& outOpaqueRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001861{
Mathias Agopian841cde52012-03-01 15:44:37 -08001862 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08001864
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001865 Region aboveOpaqueLayers;
1866 Region aboveCoveredLayers;
1867 Region dirty;
1868
Mathias Agopian87baae12012-07-31 12:38:26 -07001869 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001870
1871 size_t i = currentLayers.size();
1872 while (i--) {
Mathias Agopian13127d82013-03-05 17:47:11 -08001873 const sp<Layer>& layer = currentLayers[i];
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001874
1875 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07001876 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001877
Jesse Hall01e29052013-02-19 16:13:35 -08001878 // only consider the layers on the given layer stack
Mathias Agopian87baae12012-07-31 12:38:26 -07001879 if (s.layerStack != layerStack)
1880 continue;
1881
Mathias Agopianab028732010-03-16 16:41:46 -07001882 /*
1883 * opaqueRegion: area of a surface that is fully opaque.
1884 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001885 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001886
1887 /*
1888 * visibleRegion: area of a surface that is visible on screen
1889 * and not fully transparent. This is essentially the layer's
1890 * footprint minus the opaque regions above it.
1891 * Areas covered by a translucent surface are considered visible.
1892 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001893 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001894
1895 /*
1896 * coveredRegion: area of a surface that is covered by all
1897 * visible regions above it (which includes the translucent areas).
1898 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001899 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001900
Jesse Halla8026d22012-09-25 13:25:04 -07001901 /*
1902 * transparentRegion: area of a surface that is hinted to be completely
1903 * transparent. This is only used to tell when the layer has no visible
1904 * non-transparent regions and can be removed from the layer list. It
1905 * does not affect the visibleRegion of this layer or any layers
1906 * beneath it. The hint may not be correct if apps don't respect the
1907 * SurfaceView restrictions (which, sadly, some don't).
1908 */
1909 Region transparentRegion;
1910
Mathias Agopianab028732010-03-16 16:41:46 -07001911
1912 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07001913 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08001914 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001915 Rect bounds(s.active.transform.transform(layer->computeBounds()));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001916 visibleRegion.set(bounds);
Mathias Agopianab028732010-03-16 16:41:46 -07001917 if (!visibleRegion.isEmpty()) {
1918 // Remove the transparent area from the visible region
1919 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001920 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001921 if (tr.preserveRects()) {
1922 // transform the transparent region
1923 transparentRegion = tr.transform(s.activeTransparentRegion);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001924 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001925 // transformation too complex, can't do the
1926 // transparent region optimization.
1927 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001928 }
Mathias Agopianab028732010-03-16 16:41:46 -07001929 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001930
Mathias Agopianab028732010-03-16 16:41:46 -07001931 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001932 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001933 if (s.alpha == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07001934 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1935 // the opaque region is the layer's footprint
1936 opaqueRegion = visibleRegion;
1937 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001938 }
1939 }
1940
Mathias Agopianab028732010-03-16 16:41:46 -07001941 // Clip the covered region to the visible region
1942 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1943
1944 // Update aboveCoveredLayers for next (lower) layer
1945 aboveCoveredLayers.orSelf(visibleRegion);
1946
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001947 // subtract the opaque region covered by the layers above us
1948 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001949
1950 // compute this layer's dirty region
1951 if (layer->contentDirty) {
1952 // we need to invalidate the whole region
1953 dirty = visibleRegion;
1954 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07001955 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001956 layer->contentDirty = false;
1957 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001958 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07001959 * the exposed region consists of two components:
1960 * 1) what's VISIBLE now and was COVERED before
1961 * 2) what's EXPOSED now less what was EXPOSED before
1962 *
1963 * note that (1) is conservative, we start with the whole
1964 * visible region but only keep what used to be covered by
1965 * something -- which mean it may have been exposed.
1966 *
1967 * (2) handles areas that were not covered by anything but got
1968 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07001969 */
Mathias Agopianab028732010-03-16 16:41:46 -07001970 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001971 const Region oldVisibleRegion = layer->visibleRegion;
1972 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07001973 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1974 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001975 }
1976 dirty.subtractSelf(aboveOpaqueLayers);
1977
1978 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07001979 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001980
Mathias Agopianab028732010-03-16 16:41:46 -07001981 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001982 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07001983
Jesse Halla8026d22012-09-25 13:25:04 -07001984 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001985 layer->setVisibleRegion(visibleRegion);
1986 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07001987 layer->setVisibleNonTransparentRegion(
1988 visibleRegion.subtract(transparentRegion));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001989 }
1990
Mathias Agopian87baae12012-07-31 12:38:26 -07001991 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001992}
1993
Mathias Agopian87baae12012-07-31 12:38:26 -07001994void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1995 const Region& dirty) {
Mathias Agopian92a979a2012-08-02 18:32:23 -07001996 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
Mathias Agopian42977342012-08-05 00:40:46 -07001997 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1998 if (hw->getLayerStack() == layerStack) {
1999 hw->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002000 }
2001 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002002}
2003
Dan Stoza6b9454d2014-11-07 16:00:59 -08002004bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002005{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002006 ALOGV("handlePageFlip");
2007
Mathias Agopian4fec8732012-06-29 14:12:52 -07002008 Region dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002009
Mathias Agopian4fec8732012-06-29 14:12:52 -07002010 bool visibleRegions = false;
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002011 const LayerVector& layers(mDrawingState.layersSortedByZ);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002012 bool frameQueued = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002013
2014 // Store the set of layers that need updates. This set must not change as
2015 // buffers are being latched, as this could result in a deadlock.
2016 // Example: Two producers share the same command stream and:
2017 // 1.) Layer 0 is latched
2018 // 2.) Layer 0 gets a new frame
2019 // 2.) Layer 1 gets a new frame
2020 // 3.) Layer 1 is latched.
2021 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2022 // second frame. But layer 0's second frame could be waiting on display.
Eric Penner51c59cd2014-07-28 19:51:58 -07002023 for (size_t i = 0, count = layers.size(); i<count ; i++) {
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002024 const sp<Layer>& layer(layers[i]);
Dan Stoza6b9454d2014-11-07 16:00:59 -08002025 if (layer->hasQueuedFrame()) {
2026 frameQueued = true;
2027 if (layer->shouldPresentNow(mPrimaryDispSync)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002028 mLayersWithQueuedFrames.push_back(layer.get());
Dan Stozaee44edd2015-03-23 15:50:23 -07002029 } else {
2030 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002031 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002032 } else {
2033 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002034 }
Eric Penner51c59cd2014-07-28 19:51:58 -07002035 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002036 for (auto& layer : mLayersWithQueuedFrames) {
Mathias Agopian87baae12012-07-31 12:38:26 -07002037 const Region dirty(layer->latchBuffer(visibleRegions));
Dan Stozaee44edd2015-03-23 15:50:23 -07002038 layer->useSurfaceDamage();
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002039 const Layer::State& s(layer->getDrawingState());
Mathias Agopian87baae12012-07-31 12:38:26 -07002040 invalidateLayerStack(s.layerStack, dirty);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002041 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002042
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002043 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002044
2045 // If we will need to wake up at some time in the future to deal with a
2046 // queued frame that shouldn't be displayed during this vsync period, wake
2047 // up during the next vsync period to check again.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002048 if (frameQueued && mLayersWithQueuedFrames.empty()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002049 signalLayerUpdate();
2050 }
2051
2052 // Only continue with the refresh if there is actually new work to do
Dan Stoza9e56aa02015-11-02 13:00:03 -08002053 return !mLayersWithQueuedFrames.empty();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002054}
2055
Mathias Agopianad456f92011-01-13 17:53:01 -08002056void SurfaceFlinger::invalidateHwcGeometry()
2057{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002058 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002059}
2060
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002061
Mathias Agopiancd60f992012-08-16 16:28:27 -07002062void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
Mathias Agopian87baae12012-07-31 12:38:26 -07002063 const Region& inDirtyRegion)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002064{
Dan Stoza71433162014-02-04 16:22:36 -08002065 // We only need to actually compose the display if:
2066 // 1) It is being handled by hardware composer, which may need this to
2067 // keep its virtual display state machine in sync, or
2068 // 2) There is work to be done (the dirty region isn't empty)
2069 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
2070 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002071 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002072 return;
2073 }
2074
Dan Stoza9e56aa02015-11-02 13:00:03 -08002075 ALOGV("doDisplayComposition");
2076
Mathias Agopian87baae12012-07-31 12:38:26 -07002077 Region dirtyRegion(inDirtyRegion);
2078
Mathias Agopianb8a55602009-06-26 19:06:36 -07002079 // compute the invalid region
Mathias Agopian42977342012-08-05 00:40:46 -07002080 hw->swapRegion.orSelf(dirtyRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002081
Mathias Agopian42977342012-08-05 00:40:46 -07002082 uint32_t flags = hw->getFlags();
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002083 if (flags & DisplayDevice::SWAP_RECTANGLE) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002084 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
2085 // takes a rectangle, we must make sure to update that whole
2086 // rectangle in that case
Mathias Agopian42977342012-08-05 00:40:46 -07002087 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002088 } else {
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002089 if (flags & DisplayDevice::PARTIAL_UPDATES) {
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002090 // We need to redraw the rectangle that will be updated
2091 // (pushed to the framebuffer).
Mathias Agopian95a666b2009-09-24 14:57:26 -07002092 // This is needed because PARTIAL_UPDATES only takes one
Mathias Agopian0f2f5ff2012-07-31 23:09:07 -07002093 // rectangle instead of a region (see DisplayDevice::flip())
Mathias Agopian42977342012-08-05 00:40:46 -07002094 dirtyRegion.set(hw->swapRegion.bounds());
Mathias Agopian29d06ac2009-06-29 18:49:56 -07002095 } else {
2096 // we need to redraw everything (the whole screen)
Mathias Agopian42977342012-08-05 00:40:46 -07002097 dirtyRegion.set(hw->bounds());
2098 hw->swapRegion = dirtyRegion;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002099 }
2100 }
2101
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002102 if (!doComposeSurfaces(hw, dirtyRegion)) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002103
Mathias Agopian9c6e2972011-09-20 17:21:56 -07002104 // update the swap region and clear the dirty region
Mathias Agopian42977342012-08-05 00:40:46 -07002105 hw->swapRegion.orSelf(dirtyRegion);
Mathias Agopianda27af92012-09-13 18:17:13 -07002106
2107 // swap buffers (presentation)
2108 hw->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002109}
2110
Dan Stoza9e56aa02015-11-02 13:00:03 -08002111bool SurfaceFlinger::doComposeSurfaces(
2112 const sp<const DisplayDevice>& displayDevice, const Region& dirty)
Mathias Agopianf384cc32011-09-08 18:31:55 -07002113{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002114 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002115
Dan Stoza9e56aa02015-11-02 13:00:03 -08002116 const auto hwcId = displayDevice->getHwcDisplayId();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002117
2118 mat4 oldColorMatrix;
2119 const bool applyColorMatrix = !mHwc->hasDeviceComposition(hwcId) &&
2120 !mHwc->hasCapability(HWC2::Capability::SkipClientColorTransform);
2121 if (applyColorMatrix) {
2122 mat4 colorMatrix = mColorMatrix * mDaltonizer();
2123 oldColorMatrix = getRenderEngine().setupColorTransform(colorMatrix);
2124 }
2125
Dan Stoza9e56aa02015-11-02 13:00:03 -08002126 bool hasClientComposition = mHwc->hasClientComposition(hwcId);
2127 if (hasClientComposition) {
2128 ALOGV("hasClientComposition");
2129
2130 if (!displayDevice->makeCurrent(mEGLDisplay, mEGLContext)) {
Michael Chockc8c71092013-03-04 15:15:46 -08002131 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 displayDevice->getDisplayName().string());
Michael Lentine3f121fc2014-10-01 11:17:28 -07002133 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
2134 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2135 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2136 }
2137 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002138 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002139
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002140 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002141 const bool hasDeviceComposition = mHwc->hasDeviceComposition(hwcId);
2142 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002143 // when using overlays, we assume a fully transparent framebuffer
2144 // NOTE: we could reduce how much we need to clear, for instance
2145 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002146 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002147 // We'll revisit later if needed.
Dan Stoza9e56aa02015-11-02 13:00:03 -08002148 mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002149 } else {
Mathias Agopian766dc492012-10-30 18:08:06 -07002150 // we start with the whole screen area
Dan Stoza9e56aa02015-11-02 13:00:03 -08002151 const Region bounds(displayDevice->getBounds());
Mathias Agopian766dc492012-10-30 18:08:06 -07002152
2153 // we remove the scissor part
2154 // we're left with the letterbox region
2155 // (common case is that letterbox ends-up being empty)
Dan Stoza9e56aa02015-11-02 13:00:03 -08002156 const Region letterbox(bounds.subtract(displayDevice->getScissor()));
Mathias Agopian766dc492012-10-30 18:08:06 -07002157
2158 // compute the area to clear
Dan Stoza9e56aa02015-11-02 13:00:03 -08002159 Region region(displayDevice->undefinedRegion.merge(letterbox));
Mathias Agopian766dc492012-10-30 18:08:06 -07002160
2161 // but limit it to the dirty region
2162 region.andSelf(dirty);
2163
Mathias Agopianb9494d52012-04-18 02:28:45 -07002164 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07002165 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002166 // can happen with SurfaceView
Dan Stoza9e56aa02015-11-02 13:00:03 -08002167 drawWormhole(displayDevice, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07002168 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07002169 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002170
Dan Stoza9e56aa02015-11-02 13:00:03 -08002171 if (displayDevice->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
Mathias Agopian766dc492012-10-30 18:08:06 -07002172 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07002173 // scissor on the main display. It should never be needed
2174 // anyways (though in theory it could since the API allows it).
Dan Stoza9e56aa02015-11-02 13:00:03 -08002175 const Rect& bounds(displayDevice->getBounds());
2176 const Rect& scissor(displayDevice->getScissor());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002177 if (scissor != bounds) {
2178 // scissor doesn't match the screen's dimensions, so we
2179 // need to clear everything outside of it and enable
2180 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07002181
Mathias Agopianf45c5102012-10-24 16:29:17 -07002182 // enable scissor for this frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002183 const uint32_t height = displayDevice->getHeight();
2184 mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07002185 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07002186 }
2187 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002188 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002189
Mathias Agopian85d751c2012-08-29 16:59:24 -07002190 /*
2191 * and then, render the layers targeted at the framebuffer
2192 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002193
Dan Stoza9e56aa02015-11-02 13:00:03 -08002194 ALOGV("Rendering client layers");
2195 const Transform& displayTransform = displayDevice->getTransform();
2196 if (hwcId >= 0) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002197 // we're using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 bool firstLayer = true;
2199 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
2200 const Region clip(dirty.intersect(
2201 displayTransform.transform(layer->visibleRegion)));
2202 ALOGV("Layer: %s", layer->getName().string());
2203 ALOGV(" Composition type: %s",
2204 to_string(layer->getCompositionType(hwcId)).c_str());
Mathias Agopian85d751c2012-08-29 16:59:24 -07002205 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002206 switch (layer->getCompositionType(hwcId)) {
2207 case HWC2::Composition::Cursor:
2208 case HWC2::Composition::Device:
2209 case HWC2::Composition::SolidColor: {
Mathias Agopianac683022013-10-01 15:36:52 -07002210 const Layer::State& state(layer->getDrawingState());
Dan Stoza9e56aa02015-11-02 13:00:03 -08002211 if (layer->getClearClientTarget(hwcId) && !firstLayer &&
2212 layer->isOpaque(state) && (state.alpha == 1.0f)
2213 && hasClientComposition) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002214 // never clear the very first layer since we're
2215 // guaranteed the FB is already cleared
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 layer->clearWithOpenGL(displayDevice, clip);
Mathias Agopiancd60f992012-08-16 16:28:27 -07002217 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07002218 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002219 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002220 case HWC2::Composition::Client: {
2221 layer->draw(displayDevice, clip);
Mathias Agopian85d751c2012-08-29 16:59:24 -07002222 break;
2223 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002224 default:
Mathias Agopianda27af92012-09-13 18:17:13 -07002225 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07002226 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002227 } else {
2228 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07002229 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002230 firstLayer = false;
Mathias Agopian85d751c2012-08-29 16:59:24 -07002231 }
2232 } else {
2233 // we're not using h/w composer
Dan Stoza9e56aa02015-11-02 13:00:03 -08002234 for (auto& layer : displayDevice->getVisibleLayersSortedByZ()) {
Mathias Agopian85d751c2012-08-29 16:59:24 -07002235 const Region clip(dirty.intersect(
Dan Stoza9e56aa02015-11-02 13:00:03 -08002236 displayTransform.transform(layer->visibleRegion)));
Mathias Agopian85d751c2012-08-29 16:59:24 -07002237 if (!clip.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002238 layer->draw(displayDevice, clip);
Jesse Halla6b32db2012-07-19 16:44:38 -07002239 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07002240 }
2241 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07002242
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002243 if (applyColorMatrix) {
2244 getRenderEngine().setupColorTransform(oldColorMatrix);
2245 }
2246
Mathias Agopianf45c5102012-10-24 16:29:17 -07002247 // disable scissor at the end of the frame
Dan Stoza9e56aa02015-11-02 13:00:03 -08002248 mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07002249 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002250}
2251
Mathias Agopian3f844832013-08-07 21:24:32 -07002252void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
Mathias Agopian55801e42012-08-27 18:54:24 -07002253 const int32_t height = hw->getHeight();
Mathias Agopian3f844832013-08-07 21:24:32 -07002254 RenderEngine& engine(getRenderEngine());
2255 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002256}
2257
Dan Stoza7d89d062015-04-30 13:29:25 -07002258status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08002259 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07002260 const sp<IGraphicBufferProducer>& gbc,
Mathias Agopian13127d82013-03-05 17:47:11 -08002261 const sp<Layer>& lbc)
Mathias Agopian96f08192010-06-02 23:28:45 -07002262{
Dan Stoza7d89d062015-04-30 13:29:25 -07002263 // add this layer to the current state list
2264 {
2265 Mutex::Autolock _l(mStateLock);
2266 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2267 return NO_MEMORY;
2268 }
2269 mCurrentState.layersSortedByZ.add(lbc);
2270 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2271 }
2272
Mathias Agopian96f08192010-06-02 23:28:45 -07002273 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002274 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002275
Dan Stoza7d89d062015-04-30 13:29:25 -07002276 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002277}
2278
Mathias Agopian3f844832013-08-07 21:24:32 -07002279status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002280 Mutex::Autolock _l(mStateLock);
Mathias Agopian13127d82013-03-05 17:47:11 -08002281 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002282 if (index >= 0) {
Mathias Agopian67106042013-03-14 19:18:13 -07002283 mLayersPendingRemoval.push(layer);
Mathias Agopian076b1cc2009-04-10 14:24:30 -07002284 mLayersRemoved = true;
Mathias Agopian67106042013-03-14 19:18:13 -07002285 setTransactionFlags(eTransactionNeeded);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002286 return NO_ERROR;
2287 }
Mathias Agopian3d579642009-06-04 18:46:21 -07002288 return status_t(index);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002289}
2290
Dan Stozac7014012014-02-14 15:03:43 -08002291uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
Mathias Agopiandea20b12011-05-03 17:04:02 -07002292 return android_atomic_release_load(&mTransactionFlags);
2293}
2294
Mathias Agopian3f844832013-08-07 21:24:32 -07002295uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2297}
2298
Mathias Agopian3f844832013-08-07 21:24:32 -07002299uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002300 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2301 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002302 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303 }
2304 return old;
2305}
2306
Mathias Agopian8b33f032012-07-24 20:43:54 -07002307void SurfaceFlinger::setTransactionState(
2308 const Vector<ComposerState>& state,
2309 const Vector<DisplayState>& displays,
2310 uint32_t flags)
2311{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002312 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07002313 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07002314 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002315
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002316 if (flags & eAnimation) {
2317 // For window updates that are part of an animation we must wait for
2318 // previous animation "frames" to be handled.
2319 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002320 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002321 if (CC_UNLIKELY(err != NO_ERROR)) {
2322 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002323 // caller after a few seconds.
2324 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2325 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002326 mAnimTransactionPending = false;
2327 break;
2328 }
2329 }
2330 }
2331
Mathias Agopiane57f2922012-08-09 16:29:12 -07002332 size_t count = displays.size();
2333 for (size_t i=0 ; i<count ; i++) {
2334 const DisplayState& s(displays[i]);
2335 transactionFlags |= setDisplayStateLocked(s);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002336 }
2337
Mathias Agopiane57f2922012-08-09 16:29:12 -07002338 count = state.size();
Mathias Agopian698c0872011-06-28 19:09:31 -07002339 for (size_t i=0 ; i<count ; i++) {
2340 const ComposerState& s(state[i]);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002341 // Here we need to check that the interface we're given is indeed
2342 // one of our own. A malicious client could give us a NULL
2343 // IInterface, or one of its own or even one of our own but a
2344 // different type. All these situations would cause us to crash.
2345 //
2346 // NOTE: it would be better to use RTTI as we could directly check
2347 // that we have a Client*. however, RTTI is disabled in Android.
2348 if (s.client != NULL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002349 sp<IBinder> binder = IInterface::asBinder(s.client);
Mathias Agopiand17e3b52012-10-22 14:27:45 -07002350 if (binder != NULL) {
2351 String16 desc(binder->getInterfaceDescriptor());
2352 if (desc == ISurfaceComposerClient::descriptor) {
2353 sp<Client> client( static_cast<Client *>(s.client.get()) );
2354 transactionFlags |= setClientStateLocked(client, s.state);
2355 }
2356 }
2357 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002358 }
Mathias Agopian698c0872011-06-28 19:09:31 -07002359
Robert Carr2a7dbb42016-05-24 11:41:28 -07002360 // If a synchronous transaction is explicitly requested without any changes,
2361 // force a transaction anyway. This can be used as a flush mechanism for
2362 // previous async transactions.
2363 if (transactionFlags == 0 && (flags & eSynchronous)) {
2364 transactionFlags = eTransactionNeeded;
2365 }
2366
Mathias Agopian386aa982011-11-07 21:58:03 -08002367 if (transactionFlags) {
Irvel468051e2016-06-13 16:44:44 -07002368 mInterceptor.saveLayerUpdates(state, flags);
2369
Mathias Agopian386aa982011-11-07 21:58:03 -08002370 // this triggers the transaction
2371 setTransactionFlags(transactionFlags);
2372
2373 // if this is a synchronous transaction, wait for it to take effect
2374 // before returning.
2375 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002376 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08002377 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002378 if (flags & eAnimation) {
2379 mAnimTransactionPending = true;
2380 }
2381 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08002382 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2383 if (CC_UNLIKELY(err != NO_ERROR)) {
2384 // just in case something goes wrong in SF, return to the
2385 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002386 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2387 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08002388 break;
2389 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07002390 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002391 }
2392}
2393
Mathias Agopiane57f2922012-08-09 16:29:12 -07002394uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2395{
Jesse Hall9a143922012-10-04 16:29:19 -07002396 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2397 if (dpyIdx < 0)
2398 return 0;
2399
Mathias Agopiane57f2922012-08-09 16:29:12 -07002400 uint32_t flags = 0;
Jesse Hall9a143922012-10-04 16:29:19 -07002401 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
Mathias Agopian3ee454a2012-08-27 16:28:24 -07002402 if (disp.isValid()) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002403 const uint32_t what = s.what;
2404 if (what & DisplayState::eSurfaceChanged) {
Marco Nelissen097ca272014-11-14 08:01:01 -08002405 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002406 disp.surface = s.surface;
2407 flags |= eDisplayTransactionNeeded;
2408 }
2409 }
2410 if (what & DisplayState::eLayerStackChanged) {
2411 if (disp.layerStack != s.layerStack) {
2412 disp.layerStack = s.layerStack;
2413 flags |= eDisplayTransactionNeeded;
2414 }
2415 }
Mathias Agopian00e8c7a2012-09-04 19:30:46 -07002416 if (what & DisplayState::eDisplayProjectionChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002417 if (disp.orientation != s.orientation) {
2418 disp.orientation = s.orientation;
2419 flags |= eDisplayTransactionNeeded;
2420 }
2421 if (disp.frame != s.frame) {
2422 disp.frame = s.frame;
2423 flags |= eDisplayTransactionNeeded;
2424 }
2425 if (disp.viewport != s.viewport) {
2426 disp.viewport = s.viewport;
2427 flags |= eDisplayTransactionNeeded;
2428 }
2429 }
Michael Lentine47e45402014-07-18 15:34:25 -07002430 if (what & DisplayState::eDisplaySizeChanged) {
2431 if (disp.width != s.width) {
2432 disp.width = s.width;
2433 flags |= eDisplayTransactionNeeded;
2434 }
2435 if (disp.height != s.height) {
2436 disp.height = s.height;
2437 flags |= eDisplayTransactionNeeded;
2438 }
2439 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002440 }
2441 return flags;
2442}
2443
2444uint32_t SurfaceFlinger::setClientStateLocked(
2445 const sp<Client>& client,
2446 const layer_state_t& s)
2447{
2448 uint32_t flags = 0;
Mathias Agopian13127d82013-03-05 17:47:11 -08002449 sp<Layer> layer(client->getLayerUser(s.surface));
Mathias Agopiane57f2922012-08-09 16:29:12 -07002450 if (layer != 0) {
2451 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002452 bool geometryAppliesWithResize =
2453 what & layer_state_t::eGeometryAppliesWithResize;
Mathias Agopiane57f2922012-08-09 16:29:12 -07002454 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002455 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002456 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002457 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002458 }
2459 if (what & layer_state_t::eLayerChanged) {
2460 // NOTE: index needs to be calculated before we update the state
2461 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002462 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002463 mCurrentState.layersSortedByZ.removeAt(idx);
2464 mCurrentState.layersSortedByZ.add(layer);
2465 // we need traversal (state changed)
2466 // AND transaction (list changed)
2467 flags |= eTransactionNeeded|eTraversalNeeded;
2468 }
2469 }
2470 if (what & layer_state_t::eSizeChanged) {
2471 if (layer->setSize(s.w, s.h)) {
2472 flags |= eTraversalNeeded;
2473 }
2474 }
2475 if (what & layer_state_t::eAlphaChanged) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002476 if (layer->setAlpha(s.alpha))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002477 flags |= eTraversalNeeded;
2478 }
2479 if (what & layer_state_t::eMatrixChanged) {
2480 if (layer->setMatrix(s.matrix))
2481 flags |= eTraversalNeeded;
2482 }
2483 if (what & layer_state_t::eTransparentRegionChanged) {
2484 if (layer->setTransparentRegionHint(s.transparentRegion))
2485 flags |= eTraversalNeeded;
2486 }
Dan Stoza23116082015-06-18 14:58:39 -07002487 if (what & layer_state_t::eFlagsChanged) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002488 if (layer->setFlags(s.flags, s.mask))
2489 flags |= eTraversalNeeded;
2490 }
2491 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002492 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Mathias Agopiane57f2922012-08-09 16:29:12 -07002493 flags |= eTraversalNeeded;
2494 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002495 if (what & layer_state_t::eFinalCropChanged) {
2496 if (layer->setFinalCrop(s.finalCrop))
2497 flags |= eTraversalNeeded;
2498 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002499 if (what & layer_state_t::eLayerStackChanged) {
2500 // NOTE: index needs to be calculated before we update the state
2501 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
Pablo Ceballos47db6eb2015-12-08 13:53:59 -08002502 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07002503 mCurrentState.layersSortedByZ.removeAt(idx);
2504 mCurrentState.layersSortedByZ.add(layer);
2505 // we need traversal (state changed)
2506 // AND transaction (list changed)
2507 flags |= eTransactionNeeded|eTraversalNeeded;
2508 }
2509 }
Dan Stoza7dde5992015-05-22 09:51:44 -07002510 if (what & layer_state_t::eDeferTransaction) {
2511 layer->deferTransactionUntil(s.handle, s.frameNumber);
2512 // We don't trigger a traversal here because if no other state is
2513 // changed, we don't want this to cause any more work
2514 }
Robert Carrc3574f72016-03-24 12:19:32 -07002515 if (what & layer_state_t::eOverrideScalingModeChanged) {
2516 layer->setOverrideScalingMode(s.overrideScalingMode);
2517 // We don't trigger a traversal here because if no other state is
2518 // changed, we don't want this to cause any more work
2519 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07002520 }
2521 return flags;
2522}
2523
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002524status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07002525 const String8& name,
2526 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002527 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2528 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002529{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002530 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07002531 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002532 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002533 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07002534 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002535
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002536 status_t result = NO_ERROR;
2537
2538 sp<Layer> layer;
2539
Mathias Agopian3165cc22012-08-08 19:42:09 -07002540 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2541 case ISurfaceComposerClient::eFXSurfaceNormal:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002542 result = createNormalLayer(client,
2543 name, w, h, flags, format,
2544 handle, gbp, &layer);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002545 break;
Mathias Agopian3165cc22012-08-08 19:42:09 -07002546 case ISurfaceComposerClient::eFXSurfaceDim:
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002547 result = createDimLayer(client,
2548 name, w, h, flags,
2549 handle, gbp, &layer);
2550 break;
2551 default:
2552 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 break;
2554 }
2555
Dan Stoza7d89d062015-04-30 13:29:25 -07002556 if (result != NO_ERROR) {
2557 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002558 }
Dan Stoza7d89d062015-04-30 13:29:25 -07002559
2560 result = addClientLayer(client, *handle, *gbp, layer);
2561 if (result != NO_ERROR) {
2562 return result;
2563 }
Irvel468051e2016-06-13 16:44:44 -07002564 mInterceptor.saveLayerCreate(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07002565
2566 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002567 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002568}
2569
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002570status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2571 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2572 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002573{
2574 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07002575 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576 case PIXEL_FORMAT_TRANSPARENT:
2577 case PIXEL_FORMAT_TRANSLUCENT:
2578 format = PIXEL_FORMAT_RGBA_8888;
2579 break;
2580 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07002581 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002582 break;
2583 }
2584
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002585 *outLayer = new Layer(this, client, name, w, h, flags);
2586 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2587 if (err == NO_ERROR) {
2588 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002589 *gbp = (*outLayer)->getProducer();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002590 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002591
2592 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2593 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594}
2595
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002596status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2597 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2598 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002599{
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002600 *outLayer = new LayerDim(this, client, name, w, h, flags);
2601 *handle = (*outLayer)->getHandle();
Dan Stozab9b08832014-03-13 11:55:57 -07002602 *gbp = (*outLayer)->getProducer();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07002603 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07002604}
2605
Mathias Agopianac9fa422013-02-11 16:40:36 -08002606status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002607{
Mathias Agopian67106042013-03-14 19:18:13 -07002608 // called by the window manager when it wants to remove a Layer
2609 status_t err = NO_ERROR;
2610 sp<Layer> l(client->getLayerUser(handle));
2611 if (l != NULL) {
Irvel468051e2016-06-13 16:44:44 -07002612 mInterceptor.saveLayerDelete(l);
Mathias Agopian67106042013-03-14 19:18:13 -07002613 err = removeLayer(l);
2614 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2615 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07002616 }
2617 return err;
2618}
2619
Mathias Agopian13127d82013-03-05 17:47:11 -08002620status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07002621{
Mathias Agopian67106042013-03-14 19:18:13 -07002622 // called by ~LayerCleaner() when all references to the IBinder (handle)
2623 // are gone
Mathias Agopianca4d3602011-05-19 15:38:14 -07002624 status_t err = NO_ERROR;
Mathias Agopian13127d82013-03-05 17:47:11 -08002625 sp<Layer> l(layer.promote());
Mathias Agopianca4d3602011-05-19 15:38:14 -07002626 if (l != NULL) {
Mathias Agopian67106042013-03-14 19:18:13 -07002627 err = removeLayer(l);
Steve Blocke6f43dd2012-01-06 19:20:56 +00002628 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
Mathias Agopianca4d3602011-05-19 15:38:14 -07002629 "error removing layer=%p (%s)", l.get(), strerror(-err));
2630 }
2631 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002632}
2633
Mathias Agopianb60314a2012-04-10 22:09:54 -07002634// ---------------------------------------------------------------------------
2635
Andy McFadden13a082e2012-08-24 10:16:42 -07002636void SurfaceFlinger::onInitializeDisplays() {
Jesse Hall01e29052013-02-19 16:13:35 -08002637 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07002638 Vector<ComposerState> state;
2639 Vector<DisplayState> displays;
2640 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08002641 d.what = DisplayState::eDisplayProjectionChanged |
2642 DisplayState::eLayerStackChanged;
Jesse Hall692c7232012-11-08 15:41:56 -08002643 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
Jesse Hall01e29052013-02-19 16:13:35 -08002644 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002645 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07002646 d.frame.makeInvalid();
2647 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07002648 d.width = 0;
2649 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07002650 displays.add(d);
2651 setTransactionState(state, displays, 0);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002652 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
Jamie Gennis6547ff42013-07-16 20:12:42 -07002653
Dan Stoza9e56aa02015-11-02 13:00:03 -08002654 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2655 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07002656 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Andy McFadden13a082e2012-08-24 10:16:42 -07002657}
2658
2659void SurfaceFlinger::initializeDisplays() {
2660 class MessageScreenInitialized : public MessageBase {
2661 SurfaceFlinger* flinger;
2662 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002663 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Andy McFadden13a082e2012-08-24 10:16:42 -07002664 virtual bool handler() {
2665 flinger->onInitializeDisplays();
2666 return true;
2667 }
2668 };
2669 sp<MessageBase> msg = new MessageScreenInitialized(this);
2670 postMessageAsync(msg); // we may be called from main thread, use async message
2671}
2672
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002673void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2674 int mode) {
2675 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2676 this);
2677 int32_t type = hw->getDisplayType();
2678 int currentMode = hw->getPowerMode();
Andy McFadden13a082e2012-08-24 10:16:42 -07002679
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002680 if (mode == currentMode) {
2681 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002682 return;
2683 }
2684
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002685 hw->setPowerMode(mode);
2686 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2687 ALOGW("Trying to set power mode for virtual display");
2688 return;
2689 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002690
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002691 if (currentMode == HWC_POWER_MODE_OFF) {
2692 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002693 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2694 // FIXME: eventthread only knows about the main display right now
2695 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07002696 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002697 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002699 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08002700 mHasPoweredOff = true;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002701 repaintEverything();
2702 } else if (mode == HWC_POWER_MODE_OFF) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002703 if (type == DisplayDevice::DISPLAY_PRIMARY) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07002704 disableHardwareVsync(true); // also cancels any in-progress resync
2705
Mathias Agopiancde87a32012-09-13 14:09:01 -07002706 // FIXME: eventthread only knows about the main display right now
2707 mEventThread->onScreenReleased();
2708 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002709
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002710 getHwComposer().setPowerMode(type, mode);
2711 mVisibleRegionsDirty = true;
2712 // from this point on, SF will stop drawing on this display
2713 } else {
2714 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002715 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002716}
2717
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002718void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2719 class MessageSetPowerMode: public MessageBase {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002720 SurfaceFlinger& mFlinger;
2721 sp<IBinder> mDisplay;
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002722 int mMode;
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002723 public:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002724 MessageSetPowerMode(SurfaceFlinger& flinger,
2725 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2726 mDisplay(disp) { mMode = mode; }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002727 virtual bool handler() {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002728 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002729 if (hw == NULL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002730 ALOGE("Attempt to set power mode = %d for null display %p",
Michael Lentine7306c672014-07-30 13:00:37 -07002731 mMode, mDisplay.get());
Jesse Hall9e663de2013-08-16 14:28:37 -07002732 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002733 ALOGW("Attempt to set power mode = %d for virtual display",
2734 mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002735 } else {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002736 mFlinger.setPowerModeInternal(hw, mMode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002737 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07002738 return true;
2739 }
2740 };
Prashant Malani2c9b11f2014-05-25 01:36:31 -07002741 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07002742 postMessageSync(msg);
Mathias Agopianb60314a2012-04-10 22:09:54 -07002743}
2744
2745// ---------------------------------------------------------------------------
2746
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2748{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002749 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07002750
Mathias Agopianbd115332013-04-18 16:41:04 -07002751 IPCThreadState* ipc = IPCThreadState::self();
2752 const int pid = ipc->getCallingPid();
2753 const int uid = ipc->getCallingUid();
2754 if ((uid != AID_SHELL) &&
2755 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002756 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07002757 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002759 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07002760 // (this would indicate SF is stuck, but we want to be able to
2761 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08002762 status_t err = mStateLock.timedLock(s2ns(1));
2763 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07002764 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08002765 result.appendFormat(
2766 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2767 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07002768 }
2769
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002770 bool dumpAll = true;
2771 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002772 size_t numArgs = args.size();
2773 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002774 if ((index < numArgs) &&
2775 (args[index] == String16("--list"))) {
2776 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002777 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002778 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002779 }
2780
2781 if ((index < numArgs) &&
2782 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002783 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002784 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002785 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002786 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002787
2788 if ((index < numArgs) &&
2789 (args[index] == String16("--latency-clear"))) {
2790 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02002791 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08002792 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002793 }
Andy McFaddenc751e922014-05-08 14:53:26 -07002794
2795 if ((index < numArgs) &&
2796 (args[index] == String16("--dispsync"))) {
2797 index++;
2798 mPrimaryDispSync.dump(result);
2799 dumpAll = false;
2800 }
Dan Stozab90cf072015-03-05 11:05:59 -08002801
2802 if ((index < numArgs) &&
2803 (args[index] == String16("--static-screen"))) {
2804 index++;
2805 dumpStaticScreenStats(result);
2806 dumpAll = false;
2807 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002808
2809 if ((index < numArgs) &&
2810 (args[index] == String16("--fences"))) {
2811 index++;
2812 mFenceTracker.dump(&result);
2813 dumpAll = false;
2814 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07002816
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002817 if (dumpAll) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02002818 dumpAllLocked(args, index, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08002819 }
2820
Mathias Agopian9795c422009-08-26 16:36:26 -07002821 if (locked) {
2822 mStateLock.unlock();
2823 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002824 }
2825 write(fd, result.string(), result.size());
2826 return NO_ERROR;
2827}
2828
Dan Stozac7014012014-02-14 15:03:43 -08002829void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2830 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002831{
2832 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2833 const size_t count = currentLayers.size();
2834 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002835 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02002836 result.appendFormat("%s\n", layer->getName().string());
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002837 }
2838}
2839
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002840void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02002841 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002842{
2843 String8 name;
2844 if (index < args.size()) {
2845 name = String8(args[index]);
2846 index++;
2847 }
2848
Dan Stoza9e56aa02015-11-02 13:00:03 -08002849 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
2850 const nsecs_t period = activeConfig->getVsyncPeriod();
Greg Hackmann86efcc02014-03-07 12:44:02 -08002851 result.appendFormat("%" PRId64 "\n", period);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002852
2853 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002854 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002855 } else {
2856 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2857 const size_t count = currentLayers.size();
2858 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002859 const sp<Layer>& layer(currentLayers[i]);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002860 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07002861 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002862 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002863 }
2864 }
2865}
2866
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002867void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08002868 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002869{
2870 String8 name;
2871 if (index < args.size()) {
2872 name = String8(args[index]);
2873 index++;
2874 }
2875
2876 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2877 const size_t count = currentLayers.size();
2878 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08002879 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002880 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07002881 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002882 }
2883 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002884
Svetoslavd85084b2014-03-20 10:28:31 -07002885 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08002886}
2887
Jamie Gennis6547ff42013-07-16 20:12:42 -07002888// This should only be called from the main thread. Otherwise it would need
2889// the lock and should use mCurrentState rather than mDrawingState.
2890void SurfaceFlinger::logFrameStats() {
2891 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2892 const size_t count = drawingLayers.size();
2893 for (size_t i=0 ; i<count ; i++) {
2894 const sp<Layer>& layer(drawingLayers[i]);
2895 layer->logFrameStats();
2896 }
2897
2898 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2899}
2900
Andy McFadden4803b742012-09-24 19:07:20 -07002901/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2902{
2903 static const char* config =
2904 " [sf"
Andy McFadden4803b742012-09-24 19:07:20 -07002905#ifdef HAS_CONTEXT_PRIORITY
2906 " HAS_CONTEXT_PRIORITY"
2907#endif
2908#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2909 " NEVER_DEFAULT_TO_ASYNC_MODE"
2910#endif
2911#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2912 " TARGET_DISABLE_TRIPLE_BUFFERING"
2913#endif
2914 "]";
2915 result.append(config);
2916}
2917
Dan Stozab90cf072015-03-05 11:05:59 -08002918void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2919{
2920 result.appendFormat("Static screen stats:\n");
2921 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2922 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2923 float percent = 100.0f *
2924 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2925 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2926 b + 1, bucketTimeSec, percent);
2927 }
2928 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2929 float percent = 100.0f *
2930 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2931 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2932 NUM_BUCKETS - 1, bucketTimeSec, percent);
2933}
2934
Dan Stozae77c7662016-05-13 11:37:28 -07002935void SurfaceFlinger::recordBufferingStats(const char* layerName,
2936 std::vector<OccupancyTracker::Segment>&& history) {
2937 Mutex::Autolock lock(mBufferingStatsMutex);
2938 auto& stats = mBufferingStats[layerName];
2939 for (const auto& segment : history) {
2940 if (!segment.usedThirdBuffer) {
2941 stats.twoBufferTime += segment.totalTime;
2942 }
2943 if (segment.occupancyAverage < 1.0f) {
2944 stats.doubleBufferedTime += segment.totalTime;
2945 } else if (segment.occupancyAverage < 2.0f) {
2946 stats.tripleBufferedTime += segment.totalTime;
2947 }
2948 ++stats.numSegments;
2949 stats.totalTime += segment.totalTime;
2950 }
2951}
2952
2953void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2954 result.append("Buffering stats:\n");
2955 result.append(" [Layer name] <Active time> <Two buffer> "
2956 "<Double buffered> <Triple buffered>\n");
2957 Mutex::Autolock lock(mBufferingStatsMutex);
2958 typedef std::tuple<std::string, float, float, float> BufferTuple;
2959 std::map<float, BufferTuple, std::greater<float>> sorted;
2960 for (const auto& statsPair : mBufferingStats) {
2961 const char* name = statsPair.first.c_str();
2962 const BufferingStats& stats = statsPair.second;
2963 if (stats.numSegments == 0) {
2964 continue;
2965 }
2966 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2967 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2968 stats.totalTime;
2969 float doubleBufferRatio = static_cast<float>(
2970 stats.doubleBufferedTime) / stats.totalTime;
2971 float tripleBufferRatio = static_cast<float>(
2972 stats.tripleBufferedTime) / stats.totalTime;
2973 sorted.insert({activeTime, {name, twoBufferRatio,
2974 doubleBufferRatio, tripleBufferRatio}});
2975 }
2976 for (const auto& sortedPair : sorted) {
2977 float activeTime = sortedPair.first;
2978 const BufferTuple& values = sortedPair.second;
2979 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2980 std::get<0>(values).c_str(), activeTime,
2981 std::get<1>(values), std::get<2>(values),
2982 std::get<3>(values));
2983 }
2984 result.append("\n");
2985}
2986
2987
Mathias Agopian74d211a2013-04-22 16:55:35 +02002988void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2989 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08002990{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02002991 bool colorize = false;
2992 if (index < args.size()
2993 && (args[index] == String16("--color"))) {
2994 colorize = true;
2995 index++;
2996 }
2997
2998 Colorizer colorizer(colorize);
2999
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003000 // figure out if we're stuck somewhere
3001 const nsecs_t now = systemTime();
3002 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
3003 const nsecs_t inTransaction(mDebugInTransaction);
3004 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
3005 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
3006
3007 /*
Andy McFadden4803b742012-09-24 19:07:20 -07003008 * Dump library configuration.
3009 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003010
3011 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003012 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003013 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07003014 appendSfConfigString(result);
3015 appendUiConfigString(result);
3016 appendGuiConfigString(result);
3017 result.append("\n");
3018
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003019 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003020 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003021 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07003022 result.append(SyncFeatures::getInstance().toString());
3023 result.append("\n");
3024
Dan Stoza9e56aa02015-11-02 13:00:03 -08003025 const auto& activeConfig = mHwc->getActiveConfig(HWC_DISPLAY_PRIMARY);
3026
Andy McFadden41d67d72014-04-25 16:58:34 -07003027 colorizer.bold(result);
3028 result.append("DispSync configuration: ");
3029 colorizer.reset(result);
Jesse Hall24cd98e2014-07-13 14:37:16 -07003030 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
3031 "present offset %d ns (refresh %" PRId64 " ns)",
Dan Stoza9e56aa02015-11-02 13:00:03 -08003032 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
3033 PRESENT_TIME_OFFSET_FROM_VSYNC_NS, activeConfig->getVsyncPeriod());
Andy McFadden41d67d72014-04-25 16:58:34 -07003034 result.append("\n");
3035
Dan Stozab90cf072015-03-05 11:05:59 -08003036 // Dump static screen stats
3037 result.append("\n");
3038 dumpStaticScreenStats(result);
3039 result.append("\n");
3040
Dan Stozae77c7662016-05-13 11:37:28 -07003041 dumpBufferingStats(result);
3042
Andy McFadden4803b742012-09-24 19:07:20 -07003043 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003044 * Dump the visible layer list
3045 */
3046 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3047 const size_t count = currentLayers.size();
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003048 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003049 result.appendFormat("Visible layers (count = %zu)\n", count);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003050 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003051 for (size_t i=0 ; i<count ; i++) {
Mathias Agopian13127d82013-03-05 17:47:11 -08003052 const sp<Layer>& layer(currentLayers[i]);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003053 layer->dump(result, colorizer);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003054 }
3055
3056 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003057 * Dump Display state
3058 */
3059
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003060 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08003061 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003062 colorizer.reset(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003063 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
3064 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003065 hw->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07003066 }
3067
3068 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003069 * Dump SurfaceFlinger global state
3070 */
3071
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003072 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003073 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003074 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003075
Mathias Agopian888c8222012-08-04 21:10:38 -07003076 HWComposer& hwc(getHwComposer());
Mathias Agopian42977342012-08-05 00:40:46 -07003077 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
Mathias Agopianca088332013-03-28 17:44:13 -07003078
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003079 colorizer.bold(result);
3080 result.appendFormat("EGL implementation : %s\n",
3081 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
3082 colorizer.reset(result);
3083 result.appendFormat("%s\n",
Mathias Agopianca088332013-03-28 17:44:13 -07003084 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
Mathias Agopianca088332013-03-28 17:44:13 -07003085
Mathias Agopian875d8e12013-06-07 15:35:48 -07003086 mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003087
Mathias Agopian42977342012-08-05 00:40:46 -07003088 hw->undefinedRegion.dump(result, "undefinedRegion");
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003089 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3090 hw->getOrientation(), hw->isDisplayOn());
Mathias Agopian74d211a2013-04-22 16:55:35 +02003091 result.appendFormat(
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003092 " last eglSwapBuffers() time: %f us\n"
3093 " last transaction time : %f us\n"
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003094 " transaction-flags : %08x\n"
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003095 " refresh-rate : %f fps\n"
3096 " x-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003097 " y-dpi : %f\n"
Mathias Agopianed985572013-03-22 00:24:39 -07003098 " gpu_to_cpu_unsupported : %d\n"
3099 ,
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003100 mLastSwapBufferTime/1000.0,
3101 mLastTransactionTime/1000.0,
Mathias Agopianc95dbdc2012-02-05 00:19:27 -08003102 mTransactionFlags,
Dan Stoza9e56aa02015-11-02 13:00:03 -08003103 1e9 / activeConfig->getVsyncPeriod(),
3104 activeConfig->getDpiX(),
3105 activeConfig->getDpiY(),
Mathias Agopianed985572013-03-22 00:24:39 -07003106 !mGpuToCpuSupported);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003107
Mathias Agopian74d211a2013-04-22 16:55:35 +02003108 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003109 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003110
Mathias Agopian74d211a2013-04-22 16:55:35 +02003111 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003112 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003113
3114 /*
3115 * VSYNC state
3116 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02003117 mEventThread->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003118
3119 /*
3120 * Dump HWComposer state
3121 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003122 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02003123 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02003124 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003125 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003126 result.appendFormat(" h/w composer %s\n",
3127 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02003128 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003129
3130 /*
3131 * Dump gralloc state
3132 */
3133 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3134 alloc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003135}
3136
Mathias Agopian13127d82013-03-05 17:47:11 -08003137const Vector< sp<Layer> >&
Jesse Hall48bc05b2013-03-21 14:06:52 -07003138SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07003139 // Note: mStateLock is held here
Jesse Hall48bc05b2013-03-21 14:06:52 -07003140 wp<IBinder> dpy;
3141 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3142 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3143 dpy = mDisplays.keyAt(i);
3144 break;
3145 }
3146 }
3147 if (dpy == NULL) {
3148 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3149 // Just use the primary display so we have something to return
3150 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3151 }
3152 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
Mathias Agopiancb558572012-10-04 15:58:54 -07003153}
3154
Keun young Park63f165f2012-08-31 10:53:36 -07003155bool SurfaceFlinger::startDdmConnection()
3156{
3157 void* libddmconnection_dso =
3158 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3159 if (!libddmconnection_dso) {
3160 return false;
3161 }
3162 void (*DdmConnection_start)(const char* name);
3163 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07003164 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07003165 if (!DdmConnection_start) {
3166 dlclose(libddmconnection_dso);
3167 return false;
3168 }
3169 (*DdmConnection_start)(getServiceName());
3170 return true;
3171}
3172
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003173status_t SurfaceFlinger::onTransact(
3174 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3175{
3176 switch (code) {
3177 case CREATE_CONNECTION:
Mathias Agopian041a0752013-03-15 18:31:56 -07003178 case CREATE_DISPLAY:
Mathias Agopian698c0872011-06-28 19:09:31 -07003179 case SET_TRANSACTION_STATE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07003181 case CLEAR_ANIMATION_FRAME_STATS:
3182 case GET_ANIMATION_FRAME_STATS:
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003183 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003184 case GET_HDR_CAPABILITIES:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003185 {
3186 // codes that require permission check
3187 IPCThreadState* ipc = IPCThreadState::self();
3188 const int pid = ipc->getCallingPid();
Mathias Agopiana1ecca92009-05-21 19:21:59 -07003189 const int uid = ipc->getCallingUid();
Jeff Brown3bfe51d2015-04-10 20:20:13 -07003190 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Mathias Agopian99b49842011-06-27 16:05:52 -07003191 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003192 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003193 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3194 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003195 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003196 break;
3197 }
3198 case CAPTURE_SCREEN:
3199 {
3200 // codes that require permission check
3201 IPCThreadState* ipc = IPCThreadState::self();
3202 const int pid = ipc->getCallingPid();
3203 const int uid = ipc->getCallingUid();
Mathias Agopian99b49842011-06-27 16:05:52 -07003204 if ((uid != AID_GRAPHICS) &&
3205 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
Steve Blocke6f43dd2012-01-06 19:20:56 +00003206 ALOGE("Permission Denial: "
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003207 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3208 return PERMISSION_DENIED;
3209 }
3210 break;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003211 }
3212 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003214 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3215 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07003216 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Glenn Kasten99ed2242011-12-15 09:51:17 -08003217 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07003218 IPCThreadState* ipc = IPCThreadState::self();
3219 const int pid = ipc->getCallingPid();
3220 const int uid = ipc->getCallingUid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00003221 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07003222 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223 return PERMISSION_DENIED;
3224 }
3225 int n;
3226 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07003227 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07003228 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003229 return NO_ERROR;
3230 case 1002: // SHOW_UPDATES
3231 n = data.readInt32();
3232 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07003233 invalidateHwcGeometry();
3234 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003235 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07003237 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003238 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003239 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003240 case 1005:{ // force transaction
Mathias Agopiane57f2922012-08-09 16:29:12 -07003241 setTransactionFlags(
3242 eTransactionNeeded|
3243 eDisplayTransactionNeeded|
3244 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003245 return NO_ERROR;
3246 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08003247 case 1006:{ // send empty update
3248 signalRefresh();
3249 return NO_ERROR;
3250 }
Mathias Agopian53331da2011-08-22 21:44:41 -07003251 case 1008: // toggle use of hw composer
3252 n = data.readInt32();
3253 mDebugDisableHWC = n ? 1 : 0;
3254 invalidateHwcGeometry();
3255 repaintEverything();
3256 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07003257 case 1009: // toggle use of transform hint
3258 n = data.readInt32();
3259 mDebugDisableTransformHint = n ? 1 : 0;
3260 invalidateHwcGeometry();
3261 repaintEverything();
3262 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003263 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07003264 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003265 reply->writeInt32(0);
3266 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003267 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08003268 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003269 return NO_ERROR;
3270 case 1013: {
3271 Mutex::Autolock _l(mStateLock);
Mathias Agopian42977342012-08-05 00:40:46 -07003272 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3273 reply->writeInt32(hw->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07003274 return NO_ERROR;
3275 }
3276 case 1014: {
3277 // daltonize
3278 n = data.readInt32();
3279 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003280 case 1:
3281 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3282 break;
3283 case 2:
3284 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3285 break;
3286 case 3:
3287 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3288 break;
3289 default:
3290 mDaltonizer.setType(ColorBlindnessType::None);
3291 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07003292 }
3293 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003294 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003295 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003296 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07003297 }
Mathias Agopianff2ed702013-09-01 21:36:12 -07003298 invalidateHwcGeometry();
3299 repaintEverything();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003300 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003302 case 1015: {
3303 // apply a color matrix
3304 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07003305 if (n) {
3306 // color matrix is sent as mat3 matrix followed by vec3
3307 // offset, then packed into a mat4 where the last row is
3308 // the offset and extra values are 0
Alan Viverette794c5ba2013-10-03 16:40:52 -07003309 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003310 for (size_t j = 0; j < 4; j++) {
3311 mColorMatrix[i][j] = data.readFloat();
3312 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003313 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07003314 } else {
3315 mColorMatrix = mat4();
3316 }
3317 invalidateHwcGeometry();
3318 repaintEverything();
3319 return NO_ERROR;
3320 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003321 // This is an experimental interface
3322 // Needs to be shifted to proper binder interface when we productize
3323 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07003324 n = data.readInt32();
3325 mPrimaryDispSync.setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07003326 return NO_ERROR;
3327 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003328 case 1017: {
3329 n = data.readInt32();
3330 mForceFullDamage = static_cast<bool>(n);
3331 return NO_ERROR;
3332 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07003333 case 1018: { // Modify Choreographer's phase offset
3334 n = data.readInt32();
3335 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3336 return NO_ERROR;
3337 }
3338 case 1019: { // Modify SurfaceFlinger's phase offset
3339 n = data.readInt32();
3340 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3341 return NO_ERROR;
3342 }
Irvel468051e2016-06-13 16:44:44 -07003343 case 1020: { // Layer updates interceptor
3344 n = data.readInt32();
3345 if (n) {
3346 ALOGV("Interceptor enabled");
3347 mInterceptor.enable(mDrawingState.layersSortedByZ);
3348 }
3349 else{
3350 ALOGV("Interceptor disabled");
3351 mInterceptor.disable();
3352 }
3353 return NO_ERROR;
3354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003355 }
3356 }
3357 return err;
3358}
3359
Mathias Agopian53331da2011-08-22 21:44:41 -07003360void SurfaceFlinger::repaintEverything() {
Mathias Agopian87baae12012-07-31 12:38:26 -07003361 android_atomic_or(1, &mRepaintEverything);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003362 signalTransaction();
Mathias Agopian53331da2011-08-22 21:44:41 -07003363}
3364
Mathias Agopian59119e62010-10-11 12:37:43 -07003365// ---------------------------------------------------------------------------
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003366// Capture screen into an IGraphiBufferProducer
Mathias Agopian9daa5c92010-10-12 16:05:48 -07003367// ---------------------------------------------------------------------------
3368
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003369/* The code below is here to handle b/8734824
3370 *
3371 * We create a IGraphicBufferProducer wrapper that forwards all calls
Jesse Hallb154c422014-07-13 12:47:02 -07003372 * from the surfaceflinger thread to the calling binder thread, where they
3373 * are executed. This allows the calling thread in the calling process to be
3374 * reused and not depend on having "enough" binder threads to handle the
3375 * requests.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003376 */
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003377class GraphicProducerWrapper : public BBinder, public MessageHandler {
Jesse Hallb154c422014-07-13 12:47:02 -07003378 /* Parts of GraphicProducerWrapper are run on two different threads,
3379 * communicating by sending messages via Looper but also by shared member
3380 * data. Coherence maintenance is subtle and in places implicit (ugh).
3381 *
3382 * Don't rely on Looper's sendMessage/handleMessage providing
3383 * release/acquire semantics for any data not actually in the Message.
3384 * Data going from surfaceflinger to binder threads needs to be
3385 * synchronized explicitly.
3386 *
3387 * Barrier open/wait do provide release/acquire semantics. This provides
3388 * implicit synchronization for data coming back from binder to
3389 * surfaceflinger threads.
3390 */
3391
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003392 sp<IGraphicBufferProducer> impl;
3393 sp<Looper> looper;
3394 status_t result;
3395 bool exitPending;
3396 bool exitRequested;
Jesse Hallb154c422014-07-13 12:47:02 -07003397 Barrier barrier;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003398 uint32_t code;
3399 Parcel const* data;
3400 Parcel* reply;
3401
3402 enum {
3403 MSG_API_CALL,
3404 MSG_EXIT
3405 };
3406
3407 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003408 * Called on surfaceflinger thread. This is called by our "fake"
3409 * BpGraphicBufferProducer. We package the data and reply Parcel and
3410 * forward them to the binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003411 */
3412 virtual status_t transact(uint32_t code,
Dan Stozac7014012014-02-14 15:03:43 -08003413 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003414 this->code = code;
3415 this->data = &data;
3416 this->reply = reply;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003417 if (exitPending) {
Jesse Hallb154c422014-07-13 12:47:02 -07003418 // if we've exited, we run the message synchronously right here.
3419 // note (JH): as far as I can tell from looking at the code, this
3420 // never actually happens. if it does, i'm not sure if it happens
3421 // on the surfaceflinger or binder thread.
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003422 handleMessage(Message(MSG_API_CALL));
3423 } else {
3424 barrier.close();
Jesse Hallb154c422014-07-13 12:47:02 -07003425 // Prevent stores to this->{code, data, reply} from being
3426 // reordered later than the construction of Message.
3427 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003428 looper->sendMessage(this, Message(MSG_API_CALL));
3429 barrier.wait();
3430 }
bdeng3Xc2633ce2014-03-20 09:15:34 +08003431 return result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003432 }
3433
3434 /*
Jesse Hallb154c422014-07-13 12:47:02 -07003435 * here we run on the binder thread. All we've got to do is
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003436 * call the real BpGraphicBufferProducer.
3437 */
3438 virtual void handleMessage(const Message& message) {
Jesse Hallb154c422014-07-13 12:47:02 -07003439 int what = message.what;
3440 // Prevent reads below from happening before the read from Message
3441 atomic_thread_fence(memory_order_acquire);
3442 if (what == MSG_API_CALL) {
Marco Nelissen097ca272014-11-14 08:01:01 -08003443 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003444 barrier.open();
Jesse Hallb154c422014-07-13 12:47:02 -07003445 } else if (what == MSG_EXIT) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003446 exitRequested = true;
3447 }
3448 }
3449
3450public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003451 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Jesse Hallb154c422014-07-13 12:47:02 -07003452 : impl(impl),
3453 looper(new Looper(true)),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003454 result(NO_ERROR),
Jesse Hallb154c422014-07-13 12:47:02 -07003455 exitPending(false),
Pablo Ceballos53390e12015-08-04 11:25:59 -07003456 exitRequested(false),
3457 code(0),
3458 data(NULL),
3459 reply(NULL)
Jesse Hallb154c422014-07-13 12:47:02 -07003460 {}
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003461
Jesse Hallb154c422014-07-13 12:47:02 -07003462 // Binder thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003463 status_t waitForResponse() {
3464 do {
3465 looper->pollOnce(-1);
3466 } while (!exitRequested);
3467 return result;
3468 }
3469
Jesse Hallb154c422014-07-13 12:47:02 -07003470 // Client thread
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003471 void exit(status_t result) {
Mike J. Chenaaff4ef2013-07-30 10:19:24 -07003472 this->result = result;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003473 exitPending = true;
Jesse Hallb154c422014-07-13 12:47:02 -07003474 // Ensure this->result is visible to the binder thread before it
3475 // handles the message.
3476 atomic_thread_fence(memory_order_release);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003477 looper->sendMessage(this, Message(MSG_EXIT));
3478 }
3479};
3480
3481
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003482status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3483 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003484 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003485 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003486 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003487
3488 if (CC_UNLIKELY(display == 0))
3489 return BAD_VALUE;
3490
3491 if (CC_UNLIKELY(producer == 0))
3492 return BAD_VALUE;
3493
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003494 // if we have secure windows on this display, never allow the screen capture
3495 // unless the producer interface is local (i.e.: we can take a screenshot for
3496 // ourselves).
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003497 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
Mathias Agopian5ff5a842013-08-13 15:55:43 -07003498
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003499 // Convert to surfaceflinger's internal rotation type.
3500 Transform::orientation_flags rotationFlags;
3501 switch (rotation) {
3502 case ISurfaceComposer::eRotateNone:
3503 rotationFlags = Transform::ROT_0;
3504 break;
3505 case ISurfaceComposer::eRotate90:
3506 rotationFlags = Transform::ROT_90;
3507 break;
3508 case ISurfaceComposer::eRotate180:
3509 rotationFlags = Transform::ROT_180;
3510 break;
3511 case ISurfaceComposer::eRotate270:
3512 rotationFlags = Transform::ROT_270;
3513 break;
3514 default:
3515 rotationFlags = Transform::ROT_0;
3516 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3517 break;
3518 }
3519
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003520 class MessageCaptureScreen : public MessageBase {
3521 SurfaceFlinger* flinger;
3522 sp<IBinder> display;
3523 sp<IGraphicBufferProducer> producer;
Dan Stozac1879002014-05-22 15:59:05 -07003524 Rect sourceCrop;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003525 uint32_t reqWidth, reqHeight;
3526 uint32_t minLayerZ,maxLayerZ;
Dan Stozac7014012014-02-14 15:03:43 -08003527 bool useIdentityTransform;
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003528 Transform::orientation_flags rotation;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003529 status_t result;
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003530 bool isLocalScreenshot;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003531 public:
3532 MessageCaptureScreen(SurfaceFlinger* flinger,
3533 const sp<IBinder>& display,
3534 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003535 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003536 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003537 bool useIdentityTransform,
3538 Transform::orientation_flags rotation,
3539 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003540 : flinger(flinger), display(display), producer(producer),
Dan Stozac1879002014-05-22 15:59:05 -07003541 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003542 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
Dan Stozac7014012014-02-14 15:03:43 -08003543 useIdentityTransform(useIdentityTransform),
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003544 rotation(rotation), result(PERMISSION_DENIED),
3545 isLocalScreenshot(isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003546 {
3547 }
3548 status_t getResult() const {
3549 return result;
3550 }
3551 virtual bool handler() {
3552 Mutex::Autolock _l(flinger->mStateLock);
3553 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
Dan Stozac7014012014-02-14 15:03:43 -08003554 result = flinger->captureScreenImplLocked(hw, producer,
Dan Stozac1879002014-05-22 15:59:05 -07003555 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003556 useIdentityTransform, rotation, isLocalScreenshot);
Marco Nelissen097ca272014-11-14 08:01:01 -08003557 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003558 return true;
3559 }
3560 };
3561
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003562 // this creates a "fake" BBinder which will serve as a "fake" remote
3563 // binder to receive the marshaled calls and forward them to the
3564 // real remote (a BpGraphicBufferProducer)
3565 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3566
3567 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3568 // which does the marshaling work forwards to our "fake remote" above.
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003569 sp<MessageBase> msg = new MessageCaptureScreen(this,
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003570 display, IGraphicBufferProducer::asInterface( wrapper ),
Dan Stozac1879002014-05-22 15:59:05 -07003571 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003572 useIdentityTransform, rotationFlags, isLocalScreenshot);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003573
3574 status_t res = postMessageAsync(msg);
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003575 if (res == NO_ERROR) {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07003576 res = wrapper->waitForResponse();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003577 }
3578 return res;
3579}
3580
Mathias Agopian180f10d2013-04-10 22:55:41 -07003581
3582void SurfaceFlinger::renderScreenImplLocked(
3583 const sp<const DisplayDevice>& hw,
Dan Stozac1879002014-05-22 15:59:05 -07003584 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Mathias Agopian180f10d2013-04-10 22:55:41 -07003585 uint32_t minLayerZ, uint32_t maxLayerZ,
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003586 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
Mathias Agopian180f10d2013-04-10 22:55:41 -07003587{
3588 ATRACE_CALL();
Mathias Agopian3f844832013-08-07 21:24:32 -07003589 RenderEngine& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003590
3591 // get screen geometry
Andreas Gampe89fd4f72014-11-13 14:18:56 -08003592 const int32_t hw_w = hw->getWidth();
3593 const int32_t hw_h = hw->getHeight();
3594 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
Christopher Ferris0e749792015-03-23 14:32:15 -07003595 static_cast<int32_t>(reqHeight) != hw_h;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003596
Dan Stozac1879002014-05-22 15:59:05 -07003597 // if a default or invalid sourceCrop is passed in, set reasonable values
3598 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3599 !sourceCrop.isValid()) {
3600 sourceCrop.setLeftTop(Point(0, 0));
3601 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3602 }
3603
3604 // ensure that sourceCrop is inside screen
3605 if (sourceCrop.left < 0) {
3606 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3607 }
Dan Stozabe31f442014-06-11 11:20:54 -07003608 if (sourceCrop.right > hw_w) {
3609 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
Dan Stozac1879002014-05-22 15:59:05 -07003610 }
3611 if (sourceCrop.top < 0) {
3612 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3613 }
Dan Stozabe31f442014-06-11 11:20:54 -07003614 if (sourceCrop.bottom > hw_h) {
3615 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
Dan Stozac1879002014-05-22 15:59:05 -07003616 }
3617
Mathias Agopian180f10d2013-04-10 22:55:41 -07003618 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07003619 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003620
3621 // set-up our viewport
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003622 engine.setViewportAndProjection(
3623 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07003624 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003625
3626 // redraw the screen entirely...
Mathias Agopian3f844832013-08-07 21:24:32 -07003627 engine.clearWithColor(0, 0, 0, 1);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003628
3629 const LayerVector& layers( mDrawingState.layersSortedByZ );
3630 const size_t count = layers.size();
3631 for (size_t i=0 ; i<count ; ++i) {
3632 const sp<Layer>& layer(layers[i]);
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003633 const Layer::State& state(layer->getDrawingState());
Mathias Agopian180f10d2013-04-10 22:55:41 -07003634 if (state.layerStack == hw->getLayerStack()) {
3635 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3636 if (layer->isVisible()) {
3637 if (filtering) layer->setFiltering(true);
Dan Stozac7014012014-02-14 15:03:43 -08003638 layer->draw(hw, useIdentityTransform);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003639 if (filtering) layer->setFiltering(false);
3640 }
3641 }
3642 }
3643 }
3644
Mathias Agopian931bda12013-08-28 18:11:46 -07003645 hw->setViewportAndProjection();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003646}
3647
3648
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003649status_t SurfaceFlinger::captureScreenImplLocked(
3650 const sp<const DisplayDevice>& hw,
3651 const sp<IGraphicBufferProducer>& producer,
Dan Stozac1879002014-05-22 15:59:05 -07003652 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
Dan Stozac7014012014-02-14 15:03:43 -08003653 uint32_t minLayerZ, uint32_t maxLayerZ,
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003654 bool useIdentityTransform, Transform::orientation_flags rotation,
3655 bool isLocalScreenshot)
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003656{
3657 ATRACE_CALL();
3658
Mathias Agopian180f10d2013-04-10 22:55:41 -07003659 // get screen geometry
Dan Stoza35024162015-06-09 16:44:40 -07003660 uint32_t hw_w = hw->getWidth();
3661 uint32_t hw_h = hw->getHeight();
3662
3663 if (rotation & Transform::ROT_90) {
3664 std::swap(hw_w, hw_h);
3665 }
Mathias Agopian2a9fc492013-03-01 13:42:57 -08003666
Mathias Agopian180f10d2013-04-10 22:55:41 -07003667 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3668 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3669 reqWidth, reqHeight, hw_w, hw_h);
3670 return BAD_VALUE;
3671 }
Mathias Agopianc1d1b0d2011-01-16 14:05:02 -08003672
Mathias Agopian180f10d2013-04-10 22:55:41 -07003673 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3674 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3675
Pablo Ceballosb5b35632016-02-23 11:18:51 -08003676 bool secureLayerIsVisible = false;
3677 const LayerVector& layers(mDrawingState.layersSortedByZ);
3678 const size_t count = layers.size();
3679 for (size_t i = 0 ; i < count ; ++i) {
3680 const sp<Layer>& layer(layers[i]);
3681 const Layer::State& state(layer->getDrawingState());
3682 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3683 state.z <= maxLayerZ && layer->isVisible() &&
3684 layer->isSecure()) {
3685 secureLayerIsVisible = true;
3686 }
3687 }
3688
3689 if (!isLocalScreenshot && secureLayerIsVisible) {
3690 ALOGW("FB is protected: PERMISSION_DENIED");
3691 return PERMISSION_DENIED;
3692 }
3693
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003694 // create a surface (because we're a producer, and we need to
3695 // dequeue/queue a buffer)
Jesse Hall83cafff2013-09-16 15:24:53 -07003696 sp<Surface> sur = new Surface(producer, false);
Pablo Ceballos605d15a2016-07-21 13:44:51 -07003697
3698 // Put the screenshot Surface into async mode so that
3699 // Layer::headFenceHasSignaled will always return true and we'll latch the
3700 // first buffer regardless of whether or not its acquire fence has
3701 // signaled. This is needed to avoid a race condition in the rotation
3702 // animation. See b/30209608
3703 sur->setAsyncMode(true);
3704
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003705 ANativeWindow* window = sur.get();
Mathias Agopian180f10d2013-04-10 22:55:41 -07003706
Michael Lentine5a16a622015-05-21 13:48:24 -07003707 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3708 if (result == NO_ERROR) {
Mathias Agopian3ca76f42013-08-06 16:07:33 -07003709 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3710 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Mathias Agopian180f10d2013-04-10 22:55:41 -07003711
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003712 int err = 0;
3713 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
Mathias Agopian4ceff3d2013-08-21 15:23:15 -07003714 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003715 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3716 err |= native_window_set_usage(window, usage);
Mathias Agopian180f10d2013-04-10 22:55:41 -07003717
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003718 if (err == NO_ERROR) {
3719 ANativeWindowBuffer* buffer;
3720 /* TODO: Once we have the sync framework everywhere this can use
3721 * server-side waits on the fence that dequeueBuffer returns.
3722 */
3723 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3724 if (result == NO_ERROR) {
Riley Andrews86639902014-08-15 12:27:24 -07003725 int syncFd = -1;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003726 // create an EGLImage from the buffer so we can later
3727 // turn it into a texture
3728 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3729 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3730 if (image != EGL_NO_IMAGE_KHR) {
Mathias Agopian3f844832013-08-07 21:24:32 -07003731 // this binds the given EGLImage as a framebuffer for the
3732 // duration of this scope.
3733 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3734 if (imageBond.getStatus() == NO_ERROR) {
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003735 // this will in fact render into our dequeued buffer
3736 // via an FBO, which means we didn't have to create
3737 // an EGLSurface and therefore we're not
3738 // dependent on the context's EGLConfig.
Riley Andrewsc3ebe662014-09-04 16:20:31 -07003739 renderScreenImplLocked(
3740 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3741 useIdentityTransform, rotation);
Mathias Agopiand5556842013-09-19 17:08:37 -07003742
Riley Andrews86639902014-08-15 12:27:24 -07003743 // Attempt to create a sync khr object that can produce a sync point. If that
3744 // isn't available, create a non-dupable sync object in the fallback path and
3745 // wait on it directly.
3746 EGLSyncKHR sync;
3747 if (!DEBUG_SCREENSHOTS) {
3748 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
Riley Andrews9707f4d2014-10-23 16:17:04 -07003749 // native fence fd will not be populated until flush() is done.
3750 getRenderEngine().flush();
Andy McFadden2d8d1202013-10-09 16:38:02 -07003751 } else {
Riley Andrews86639902014-08-15 12:27:24 -07003752 sync = EGL_NO_SYNC_KHR;
Andy McFadden2d8d1202013-10-09 16:38:02 -07003753 }
Riley Andrews86639902014-08-15 12:27:24 -07003754 if (sync != EGL_NO_SYNC_KHR) {
3755 // get the sync fd
3756 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3757 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3758 ALOGW("captureScreen: failed to dup sync khr object");
3759 syncFd = -1;
3760 }
3761 eglDestroySyncKHR(mEGLDisplay, sync);
3762 } else {
3763 // fallback path
3764 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3765 if (sync != EGL_NO_SYNC_KHR) {
3766 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3767 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3768 EGLint eglErr = eglGetError();
3769 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3770 ALOGW("captureScreen: fence wait timed out");
3771 } else {
3772 ALOGW_IF(eglErr != EGL_SUCCESS,
3773 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3774 }
3775 eglDestroySyncKHR(mEGLDisplay, sync);
3776 } else {
3777 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3778 }
3779 }
Mathias Agopiand5556842013-09-19 17:08:37 -07003780 if (DEBUG_SCREENSHOTS) {
3781 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3782 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3783 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3784 hw, minLayerZ, maxLayerZ);
3785 delete [] pixels;
3786 }
3787
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003788 } else {
3789 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3790 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003791 window->cancelBuffer(window, buffer, syncFd);
3792 buffer = NULL;
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003793 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003794 // destroy our image
3795 eglDestroyImageKHR(mEGLDisplay, image);
3796 } else {
3797 result = BAD_VALUE;
3798 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003799 if (buffer) {
3800 // queueBuffer takes ownership of syncFd
3801 result = window->queueBuffer(window, buffer, syncFd);
3802 }
Mathias Agopian0aea53f2013-04-24 19:03:08 +02003803 }
3804 } else {
3805 result = BAD_VALUE;
3806 }
3807 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3808 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07003809
Mathias Agopian74c40c02010-09-29 13:02:36 -07003810 return result;
3811}
3812
Mathias Agopiand5556842013-09-19 17:08:37 -07003813void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3814 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003815 if (DEBUG_SCREENSHOTS) {
Mathias Agopiand5556842013-09-19 17:08:37 -07003816 for (size_t y=0 ; y<h ; y++) {
3817 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3818 for (size_t x=0 ; x<w ; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07003819 if (p[x] != 0xFF000000) return;
3820 }
3821 }
3822 ALOGE("*** we just took a black screenshot ***\n"
3823 "requested minz=%d, maxz=%d, layerStack=%d",
3824 minLayerZ, maxLayerZ, hw->getLayerStack());
3825 const LayerVector& layers( mDrawingState.layersSortedByZ );
3826 const size_t count = layers.size();
3827 for (size_t i=0 ; i<count ; ++i) {
3828 const sp<Layer>& layer(layers[i]);
3829 const Layer::State& state(layer->getDrawingState());
3830 const bool visible = (state.layerStack == hw->getLayerStack())
3831 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3832 && (layer->isVisible());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003833 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
Mathias Agopianfee2b462013-07-03 12:34:01 -07003834 visible ? '+' : '-',
3835 i, layer->getName().string(), state.layerStack, state.z,
3836 layer->isVisible(), state.flags, state.alpha);
3837 }
3838 }
3839}
3840
Pablo Ceballosce796e72016-02-04 19:10:51 -08003841bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3842 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3843 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3844}
3845
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07003846// ---------------------------------------------------------------------------
3847
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003848SurfaceFlinger::LayerVector::LayerVector() {
3849}
3850
3851SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
Mathias Agopian13127d82013-03-05 17:47:11 -08003852 : SortedVector<sp<Layer> >(rhs) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003853}
3854
3855int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3856 const void* rhs) const
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003857{
Mathias Agopianbe246f82012-07-31 22:59:38 -07003858 // sort layers per layer-stack, then by z-order and finally by sequence
Mathias Agopian13127d82013-03-05 17:47:11 -08003859 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3860 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
Mathias Agopianbe246f82012-07-31 22:59:38 -07003861
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003862 uint32_t ls = l->getCurrentState().layerStack;
3863 uint32_t rs = r->getCurrentState().layerStack;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003864 if (ls != rs)
3865 return ls - rs;
3866
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07003867 uint32_t lz = l->getCurrentState().z;
3868 uint32_t rz = r->getCurrentState().z;
Mathias Agopianbe246f82012-07-31 22:59:38 -07003869 if (lz != rz)
3870 return lz - rz;
3871
3872 return l->sequence - r->sequence;
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003873}
3874
3875// ---------------------------------------------------------------------------
3876
Mathias Agopian3ee454a2012-08-27 16:28:24 -07003877SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
Pablo Ceballos53390e12015-08-04 11:25:59 -07003878 : type(DisplayDevice::DISPLAY_ID_INVALID),
3879 layerStack(DisplayDevice::NO_LAYER_STACK),
3880 orientation(0),
3881 width(0),
3882 height(0),
3883 isSecure(false) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003884}
3885
Pablo Ceballos53390e12015-08-04 11:25:59 -07003886SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3887 DisplayDevice::DisplayType type, bool isSecure)
3888 : type(type),
3889 layerStack(DisplayDevice::NO_LAYER_STACK),
3890 orientation(0),
3891 width(0),
3892 height(0),
3893 isSecure(isSecure) {
Mathias Agopianda8d0a52012-09-04 15:05:38 -07003894 viewport.makeInvalid();
3895 frame.makeInvalid();
Mathias Agopianb7e930d2010-06-01 15:12:58 -07003896}
3897
3898// ---------------------------------------------------------------------------
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003899
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003900}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07003901
3902
3903#if defined(__gl_h_)
3904#error "don't include gl/gl.h in this file"
3905#endif
3906
3907#if defined(__gl2_h_)
3908#error "don't include gl2/gl2.h in this file"
3909#endif