blob: 37e9e70d9d97ccc973282a1aa4e2589489e3e3e8 [file] [log] [blame]
Dan Stoza9e56aa02015-11-02 13:00:03 -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
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdint.h>
20#include <sys/types.h>
21#include <errno.h>
22#include <math.h>
23#include <dlfcn.h>
24#include <inttypes.h>
25#include <stdatomic.h>
26
27#include <EGL/egl.h>
28
29#include <cutils/log.h>
30#include <cutils/properties.h>
31
32#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryHeapBase.h>
35#include <binder/PermissionCache.h>
36
37#include <ui/DisplayInfo.h>
38#include <ui/DisplayStatInfo.h>
39
40#include <gui/BitTube.h>
41#include <gui/BufferQueue.h>
42#include <gui/GuiConfig.h>
43#include <gui/IDisplayEventConnection.h>
44#include <gui/Surface.h>
45#include <gui/GraphicBufferAlloc.h>
46
47#include <ui/GraphicBufferAllocator.h>
Dan Stozac4f471e2016-03-24 09:31:08 -070048#include <ui/HdrCapabilities.h>
Dan Stoza9e56aa02015-11-02 13:00:03 -080049#include <ui/PixelFormat.h>
50#include <ui/UiConfig.h>
51
52#include <utils/misc.h>
53#include <utils/String8.h>
54#include <utils/String16.h>
55#include <utils/StopWatch.h>
56#include <utils/Timers.h>
57#include <utils/Trace.h>
58
59#include <private/android_filesystem_config.h>
60#include <private/gui/SyncFeatures.h>
61
Michael Wright28f24d02016-07-12 13:30:53 -070062#include <set>
63
Dan Stoza9e56aa02015-11-02 13:00:03 -080064#include "Client.h"
65#include "clz.h"
66#include "Colorizer.h"
67#include "DdmConnection.h"
68#include "DisplayDevice.h"
69#include "DispSync.h"
70#include "EventControlThread.h"
71#include "EventThread.h"
72#include "Layer.h"
73#include "LayerDim.h"
74#include "SurfaceFlinger.h"
75
76#include "DisplayHardware/FramebufferSurface.h"
77#include "DisplayHardware/HWComposer.h"
78#include "DisplayHardware/VirtualDisplaySurface.h"
79
80#include "Effects/Daltonizer.h"
81
82#include "RenderEngine/RenderEngine.h"
83#include <cutils/compiler.h>
84
85#define DISPLAY_COUNT 1
86
87/*
88 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
89 * black pixels.
90 */
91#define DEBUG_SCREENSHOTS false
92
93EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
94
Evgenii Stepanov6732a8f2016-07-12 17:31:30 -070095// Workaround for b/30067360: /proc/self/environ inaccessible in SurfaceFlinger
96// => ASan fails to read ASAN_OPTIONS => alloc-dealloc-mismatch bug is not
97// suppressed and prevents the device from booting.
98#ifndef __has_feature
99#define __has_feature(x) 0
100#endif
101#if __has_feature(address_sanitizer)
102__attribute__((visibility("default")))
103extern "C" const char *__asan_default_options() {
104 return "alloc_dealloc_mismatch=0";
105}
106#endif
107
Dan Stoza9e56aa02015-11-02 13:00:03 -0800108namespace android {
109
110// This is the phase offset in nanoseconds of the software vsync event
111// relative to the vsync event reported by HWComposer. The software vsync
112// event is when SurfaceFlinger and Choreographer-based applications run each
113// frame.
114//
115// This phase offset allows adjustment of the minimum latency from application
116// wake-up (by Choregographer) time to the time at which the resulting window
117// image is displayed. This value may be either positive (after the HW vsync)
118// or negative (before the HW vsync). Setting it to 0 will result in a
119// minimum latency of two vsync periods because the app and SurfaceFlinger
120// will run just after the HW vsync. Setting it to a positive number will
121// result in the minimum latency being:
122//
123// (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
124//
125// Note that reducing this latency makes it more likely for the applications
126// to not have their window content image ready in time. When this happens
127// the latency will end up being an additional vsync period, and animations
128// will hiccup. Therefore, this latency should be tuned somewhat
129// conservatively (or at least with awareness of the trade-off being made).
130static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
131
132// This is the phase offset at which SurfaceFlinger's composition runs.
133static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
134
135// ---------------------------------------------------------------------------
136
137const String16 sHardwareTest("android.permission.HARDWARE_TEST");
138const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
139const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
140const String16 sDump("android.permission.DUMP");
141
142// ---------------------------------------------------------------------------
143
144SurfaceFlinger::SurfaceFlinger()
145 : BnSurfaceComposer(),
146 mTransactionFlags(0),
147 mTransactionPending(false),
148 mAnimTransactionPending(false),
149 mLayersRemoved(false),
150 mRepaintEverything(0),
151 mRenderEngine(NULL),
152 mBootTime(systemTime()),
153 mVisibleRegionsDirty(false),
154 mHwWorkListDirty(false),
155 mAnimCompositionPending(false),
156 mDebugRegion(0),
157 mDebugDDMS(0),
158 mDebugDisableHWC(0),
159 mDebugDisableTransformHint(0),
160 mDebugInSwapBuffers(0),
161 mLastSwapBufferTime(0),
162 mDebugInTransaction(0),
163 mLastTransactionTime(0),
164 mBootFinished(false),
165 mForceFullDamage(false),
Irvel468051e2016-06-13 16:44:44 -0700166 mInterceptor(),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000167 mPrimaryDispSync("PrimaryDispSync"),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800168 mPrimaryHWVsyncEnabled(false),
169 mHWVsyncAvailable(false),
170 mDaltonize(false),
171 mHasColorMatrix(false),
172 mHasPoweredOff(false),
173 mFrameBuckets(),
174 mTotalTime(0),
175 mLastSwapTime(0)
176{
177 ALOGI("SurfaceFlinger is starting");
178
179 // debugging stuff...
180 char value[PROPERTY_VALUE_MAX];
181
182 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
183 mGpuToCpuSupported = !atoi(value);
184
Dan Stoza9e56aa02015-11-02 13:00:03 -0800185 property_get("debug.sf.showupdates", value, "0");
186 mDebugRegion = atoi(value);
187
188 property_get("debug.sf.ddms", value, "0");
189 mDebugDDMS = atoi(value);
190 if (mDebugDDMS) {
191 if (!startDdmConnection()) {
192 // start failed, and DDMS debugging not enabled
193 mDebugDDMS = 0;
194 }
195 }
196 ALOGI_IF(mDebugRegion, "showupdates enabled");
197 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
198}
199
200void SurfaceFlinger::onFirstRef()
201{
202 mEventQueue.init(this);
203}
204
205SurfaceFlinger::~SurfaceFlinger()
206{
207 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
208 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
209 eglTerminate(display);
210}
211
212void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
213{
214 // the window manager died on us. prepare its eulogy.
215
216 // restore initial conditions (default device unblank, etc)
217 initializeDisplays();
218
219 // restart the boot-animation
220 startBootAnim();
221}
222
223sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
224{
225 sp<ISurfaceComposerClient> bclient;
226 sp<Client> client(new Client(this));
227 status_t err = client->initCheck();
228 if (err == NO_ERROR) {
229 bclient = client;
230 }
231 return bclient;
232}
233
234sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
235 bool secure)
236{
237 class DisplayToken : public BBinder {
238 sp<SurfaceFlinger> flinger;
239 virtual ~DisplayToken() {
240 // no more references, this display must be terminated
241 Mutex::Autolock _l(flinger->mStateLock);
242 flinger->mCurrentState.displays.removeItem(this);
243 flinger->setTransactionFlags(eDisplayTransactionNeeded);
244 }
245 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700246 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Dan Stoza9e56aa02015-11-02 13:00:03 -0800247 : flinger(flinger) {
248 }
249 };
250
251 sp<BBinder> token = new DisplayToken(this);
252
253 Mutex::Autolock _l(mStateLock);
254 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL, secure);
255 info.displayName = displayName;
256 mCurrentState.displays.add(token, info);
257
258 return token;
259}
260
261void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
262 Mutex::Autolock _l(mStateLock);
263
264 ssize_t idx = mCurrentState.displays.indexOfKey(display);
265 if (idx < 0) {
266 ALOGW("destroyDisplay: invalid display token");
267 return;
268 }
269
270 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
271 if (!info.isVirtualDisplay()) {
272 ALOGE("destroyDisplay called for non-virtual display");
273 return;
274 }
275
276 mCurrentState.displays.removeItemsAt(idx);
277 setTransactionFlags(eDisplayTransactionNeeded);
278}
279
280void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
281 ALOGW_IF(mBuiltinDisplays[type],
282 "Overwriting display token for display type %d", type);
283 mBuiltinDisplays[type] = new BBinder();
284 // All non-virtual displays are currently considered secure.
285 DisplayDeviceState info(type, true);
286 mCurrentState.displays.add(mBuiltinDisplays[type], info);
287}
288
289sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
290 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
291 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
292 return NULL;
293 }
294 return mBuiltinDisplays[id];
295}
296
297sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
298{
299 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
300 return gba;
301}
302
303void SurfaceFlinger::bootFinished()
304{
305 const nsecs_t now = systemTime();
306 const nsecs_t duration = now - mBootTime;
307 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
308 mBootFinished = true;
309
310 // wait patiently for the window manager death
311 const String16 name("window");
312 sp<IBinder> window(defaultServiceManager()->getService(name));
313 if (window != 0) {
314 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
315 }
316
317 // stop boot animation
318 // formerly we would just kill the process, but we now ask it to exit so it
319 // can choose where to stop the animation.
320 property_set("service.bootanim.exit", "1");
321
322 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
323 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
324 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
325}
326
327void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
328 class MessageDestroyGLTexture : public MessageBase {
329 RenderEngine& engine;
330 uint32_t texture;
331 public:
332 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
333 : engine(engine), texture(texture) {
334 }
335 virtual bool handler() {
336 engine.deleteTextures(1, &texture);
337 return true;
338 }
339 };
340 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
341}
342
343class DispSyncSource : public VSyncSource, private DispSync::Callback {
344public:
345 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000346 const char* name) :
347 mName(name),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800348 mValue(0),
349 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000350 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
351 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800352 mDispSync(dispSync),
353 mCallbackMutex(),
354 mCallback(),
355 mVsyncMutex(),
356 mPhaseOffset(phaseOffset),
357 mEnabled(false) {}
358
359 virtual ~DispSyncSource() {}
360
361 virtual void setVSyncEnabled(bool enable) {
362 Mutex::Autolock lock(mVsyncMutex);
363 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000364 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stoza9e56aa02015-11-02 13:00:03 -0800365 static_cast<DispSync::Callback*>(this));
366 if (err != NO_ERROR) {
367 ALOGE("error registering vsync callback: %s (%d)",
368 strerror(-err), err);
369 }
370 //ATRACE_INT(mVsyncOnLabel.string(), 1);
371 } else {
372 status_t err = mDispSync->removeEventListener(
373 static_cast<DispSync::Callback*>(this));
374 if (err != NO_ERROR) {
375 ALOGE("error unregistering vsync callback: %s (%d)",
376 strerror(-err), err);
377 }
378 //ATRACE_INT(mVsyncOnLabel.string(), 0);
379 }
380 mEnabled = enable;
381 }
382
383 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
384 Mutex::Autolock lock(mCallbackMutex);
385 mCallback = callback;
386 }
387
388 virtual void setPhaseOffset(nsecs_t phaseOffset) {
389 Mutex::Autolock lock(mVsyncMutex);
390
391 // Normalize phaseOffset to [0, period)
392 auto period = mDispSync->getPeriod();
393 phaseOffset %= period;
394 if (phaseOffset < 0) {
395 // If we're here, then phaseOffset is in (-period, 0). After this
396 // operation, it will be in (0, period)
397 phaseOffset += period;
398 }
399 mPhaseOffset = phaseOffset;
400
401 // If we're not enabled, we don't need to mess with the listeners
402 if (!mEnabled) {
403 return;
404 }
405
406 // Remove the listener with the old offset
407 status_t err = mDispSync->removeEventListener(
408 static_cast<DispSync::Callback*>(this));
409 if (err != NO_ERROR) {
410 ALOGE("error unregistering vsync callback: %s (%d)",
411 strerror(-err), err);
412 }
413
414 // Add a listener with the new offset
Tim Murray4a4e4a22016-04-19 16:29:23 +0000415 err = mDispSync->addEventListener(mName, mPhaseOffset,
Dan Stoza9e56aa02015-11-02 13:00:03 -0800416 static_cast<DispSync::Callback*>(this));
417 if (err != NO_ERROR) {
418 ALOGE("error registering vsync callback: %s (%d)",
419 strerror(-err), err);
420 }
421 }
422
423private:
424 virtual void onDispSyncEvent(nsecs_t when) {
425 sp<VSyncSource::Callback> callback;
426 {
427 Mutex::Autolock lock(mCallbackMutex);
428 callback = mCallback;
429
430 if (mTraceVsync) {
431 mValue = (mValue + 1) % 2;
432 ATRACE_INT(mVsyncEventLabel.string(), mValue);
433 }
434 }
435
436 if (callback != NULL) {
437 callback->onVSyncEvent(when);
438 }
439 }
440
Tim Murray4a4e4a22016-04-19 16:29:23 +0000441 const char* const mName;
442
Dan Stoza9e56aa02015-11-02 13:00:03 -0800443 int mValue;
444
445 const bool mTraceVsync;
446 const String8 mVsyncOnLabel;
447 const String8 mVsyncEventLabel;
448
449 DispSync* mDispSync;
450
451 Mutex mCallbackMutex; // Protects the following
452 sp<VSyncSource::Callback> mCallback;
453
454 Mutex mVsyncMutex; // Protects the following
455 nsecs_t mPhaseOffset;
456 bool mEnabled;
457};
458
459void SurfaceFlinger::init() {
460 ALOGI( "SurfaceFlinger's main thread ready to run. "
461 "Initializing graphics H/W...");
462
463 Mutex::Autolock _l(mStateLock);
464
465 // initialize EGL for the default display
466 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
467 eglInitialize(mEGLDisplay, NULL, NULL);
468
469 // start the EventThread
470 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
471 vsyncPhaseOffsetNs, true, "app");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000472 mEventThread = new EventThread(vsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800473 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
474 sfVsyncPhaseOffsetNs, true, "sf");
Tim Murray4a4e4a22016-04-19 16:29:23 +0000475 mSFEventThread = new EventThread(sfVsyncSrc, *this);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800476 mEventQueue.setEventThread(mSFEventThread);
477
Tim Murrayacff43d2016-07-29 13:57:24 -0700478 // set SFEventThread to SCHED_FIFO to minimize jitter
Tim Murray41a38532016-06-22 12:42:10 -0700479 struct sched_param param = {0};
480 param.sched_priority = 1;
Tim Murray41a38532016-06-22 12:42:10 -0700481 if (sched_setscheduler(mSFEventThread->getTid(), SCHED_FIFO, &param) != 0) {
482 ALOGE("Couldn't set SCHED_FIFO for SFEventThread");
483 }
484
485
Dan Stoza9e56aa02015-11-02 13:00:03 -0800486 // Initialize the H/W composer object. There may or may not be an
487 // actual hardware composer underneath.
488 mHwc = new HWComposer(this,
489 *static_cast<HWComposer::EventHandler *>(this));
490
491 // get a RenderEngine for the given display / config (can't fail)
492 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
493
494 // retrieve the EGL context that was selected/created
495 mEGLContext = mRenderEngine->getEGLContext();
496
497 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
498 "couldn't create EGLContext");
499
500 // initialize our non-virtual displays
501 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
502 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
503 // set-up the displays that are already connected
504 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
505 // All non-virtual displays are currently considered secure.
506 bool isSecure = true;
507 createBuiltinDisplayLocked(type);
508 wp<IBinder> token = mBuiltinDisplays[i];
509
510 sp<IGraphicBufferProducer> producer;
511 sp<IGraphicBufferConsumer> consumer;
512 BufferQueue::createBufferQueue(&producer, &consumer,
513 new GraphicBufferAlloc());
514
515 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
516 consumer);
517 int32_t hwcId = allocateHwcDisplayId(type);
518 sp<DisplayDevice> hw = new DisplayDevice(this,
519 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
520 fbs, producer,
521 mRenderEngine->getEGLConfig());
522 if (i > DisplayDevice::DISPLAY_PRIMARY) {
523 // FIXME: currently we don't get blank/unblank requests
524 // for displays other than the main display, so we always
525 // assume a connected display is unblanked.
526 ALOGD("marking display %zu as acquired/unblanked", i);
527 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
528 }
529 mDisplays.add(token, hw);
530 }
531 }
532
533 // make the GLContext current so that we can create textures when creating Layers
534 // (which may happens before we render something)
535 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
536
537 mEventControlThread = new EventControlThread(this);
538 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
539
540 // set a fake vsync period if there is no HWComposer
541 if (mHwc->initCheck() != NO_ERROR) {
542 mPrimaryDispSync.setPeriod(16666667);
543 }
544
545 // initialize our drawing state
546 mDrawingState = mCurrentState;
547
548 // set initial conditions (e.g. unblank default device)
549 initializeDisplays();
550
Dan Stoza4e637772016-07-28 13:31:51 -0700551 mRenderEngine->primeCache();
552
Dan Stoza9e56aa02015-11-02 13:00:03 -0800553 // start boot animation
554 startBootAnim();
555}
556
557int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
558 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
559 type : mHwc->allocateDisplayId();
560}
561
562void SurfaceFlinger::startBootAnim() {
563 // start boot animation
564 property_set("service.bootanim.exit", "0");
565 property_set("ctl.start", "bootanim");
566}
567
568size_t SurfaceFlinger::getMaxTextureSize() const {
569 return mRenderEngine->getMaxTextureSize();
570}
571
572size_t SurfaceFlinger::getMaxViewportDims() const {
573 return mRenderEngine->getMaxViewportDims();
574}
575
576// ----------------------------------------------------------------------------
577
578bool SurfaceFlinger::authenticateSurfaceTexture(
579 const sp<IGraphicBufferProducer>& bufferProducer) const {
580 Mutex::Autolock _l(mStateLock);
581 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
582 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
583}
584
585status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
586 Vector<DisplayInfo>* configs) {
587 if ((configs == NULL) || (display.get() == NULL)) {
588 return BAD_VALUE;
589 }
590
Michael Wright28f24d02016-07-12 13:30:53 -0700591 int32_t type = getDisplayType(display);
592 if (type < 0) return type;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800593
594 // TODO: Not sure if display density should handled by SF any longer
595 class Density {
596 static int getDensityFromProperty(char const* propName) {
597 char property[PROPERTY_VALUE_MAX];
598 int density = 0;
599 if (property_get(propName, property, NULL) > 0) {
600 density = atoi(property);
601 }
602 return density;
603 }
604 public:
605 static int getEmuDensity() {
606 return getDensityFromProperty("qemu.sf.lcd_density"); }
607 static int getBuildDensity() {
608 return getDensityFromProperty("ro.sf.lcd_density"); }
609 };
610
611 configs->clear();
612
613 const Vector<HWComposer::DisplayConfig>& hwConfigs =
614 getHwComposer().getConfigs(type);
615 for (size_t c = 0; c < hwConfigs.size(); ++c) {
616 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
617 DisplayInfo info = DisplayInfo();
618
619 float xdpi = hwConfig.xdpi;
620 float ydpi = hwConfig.ydpi;
621
622 if (type == DisplayDevice::DISPLAY_PRIMARY) {
623 // The density of the device is provided by a build property
624 float density = Density::getBuildDensity() / 160.0f;
625 if (density == 0) {
626 // the build doesn't provide a density -- this is wrong!
627 // use xdpi instead
628 ALOGE("ro.sf.lcd_density must be defined as a build property");
629 density = xdpi / 160.0f;
630 }
631 if (Density::getEmuDensity()) {
632 // if "qemu.sf.lcd_density" is specified, it overrides everything
633 xdpi = ydpi = density = Density::getEmuDensity();
634 density /= 160.0f;
635 }
636 info.density = density;
637
638 // TODO: this needs to go away (currently needed only by webkit)
639 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
640 info.orientation = hw->getOrientation();
641 } else {
642 // TODO: where should this value come from?
643 static const int TV_DENSITY = 213;
644 info.density = TV_DENSITY / 160.0f;
645 info.orientation = 0;
646 }
647
648 info.w = hwConfig.width;
649 info.h = hwConfig.height;
650 info.xdpi = xdpi;
651 info.ydpi = ydpi;
652 info.fps = float(1e9 / hwConfig.refresh);
653 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800654
655 // This is how far in advance a buffer must be queued for
656 // presentation at a given time. If you want a buffer to appear
657 // on the screen at time N, you must submit the buffer before
658 // (N - presentationDeadline).
659 //
660 // Normally it's one full refresh period (to give SF a chance to
661 // latch the buffer), but this can be reduced by configuring a
662 // DispSync offset. Any additional delays introduced by the hardware
663 // composer or panel must be accounted for here.
664 //
665 // We add an additional 1ms to allow for processing time and
666 // differences between the ideal and actual refresh rate.
667 info.presentationDeadline =
668 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
669
670 // All non-virtual displays are currently considered secure.
671 info.secure = true;
672
673 configs->push_back(info);
674 }
675
676 return NO_ERROR;
677}
678
679status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
680 DisplayStatInfo* stats) {
681 if (stats == NULL) {
682 return BAD_VALUE;
683 }
684
685 // FIXME for now we always return stats for the primary display
686 memset(stats, 0, sizeof(*stats));
687 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
688 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
689 return NO_ERROR;
690}
691
692int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
693 sp<DisplayDevice> device(getDisplayDevice(display));
694 if (device != NULL) {
695 return device->getActiveConfig();
696 }
697 return BAD_VALUE;
698}
699
700void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
701 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
702 this);
703 int32_t type = hw->getDisplayType();
704 int currentMode = hw->getActiveConfig();
705
706 if (mode == currentMode) {
707 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
708 return;
709 }
710
711 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
712 ALOGW("Trying to set config for virtual display");
713 return;
714 }
715
716 hw->setActiveConfig(mode);
717 getHwComposer().setActiveConfig(type, mode);
718}
719
720status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
721 class MessageSetActiveConfig: public MessageBase {
722 SurfaceFlinger& mFlinger;
723 sp<IBinder> mDisplay;
724 int mMode;
725 public:
726 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
727 int mode) :
728 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
729 virtual bool handler() {
730 Vector<DisplayInfo> configs;
731 mFlinger.getDisplayConfigs(mDisplay, &configs);
732 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
733 ALOGE("Attempt to set active config = %d for display with %zu configs",
734 mMode, configs.size());
735 }
736 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
737 if (hw == NULL) {
738 ALOGE("Attempt to set active config = %d for null display %p",
739 mMode, mDisplay.get());
740 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
741 ALOGW("Attempt to set active config = %d for virtual display",
742 mMode);
743 } else {
744 mFlinger.setActiveConfigInternal(hw, mMode);
745 }
746 return true;
747 }
748 };
749 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
750 postMessageSync(msg);
751 return NO_ERROR;
752}
753
Michael Wright28f24d02016-07-12 13:30:53 -0700754status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& display,
755 Vector<android_color_mode_t>* outColorModes) {
756 if (outColorModes == nullptr || display.get() == nullptr) {
757 return BAD_VALUE;
758 }
759
760 int32_t type = getDisplayType(display);
761 if (type < 0) return type;
762
763 std::set<android_color_mode_t> colorModes;
764 for (const HWComposer::DisplayConfig& hwConfig : getHwComposer().getConfigs(type)) {
765 colorModes.insert(hwConfig.colorMode);
766 }
767
768 outColorModes->clear();
769 std::copy(colorModes.cbegin(), colorModes.cend(), std::back_inserter(*outColorModes));
770
771 return NO_ERROR;
772}
773
774android_color_mode_t SurfaceFlinger::getActiveColorMode(const sp<IBinder>& display) {
775 if (display.get() == nullptr) return static_cast<android_color_mode_t>(BAD_VALUE);
776
777 int32_t type = getDisplayType(display);
778 if (type < 0) return static_cast<android_color_mode_t>(type);
779
780 return getHwComposer().getColorMode(type);
781}
782
783status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& display,
784 android_color_mode_t colorMode) {
785 if (display.get() == nullptr || colorMode < 0) {
786 return BAD_VALUE;
787 }
788
789 int32_t type = getDisplayType(display);
790 if (type < 0) return type;
791 const Vector<HWComposer::DisplayConfig>& hwConfigs = getHwComposer().getConfigs(type);
792 HWComposer::DisplayConfig desiredConfig = hwConfigs[getHwComposer().getCurrentConfig(type)];
793 desiredConfig.colorMode = colorMode;
794 for (size_t c = 0; c < hwConfigs.size(); ++c) {
795 const HWComposer::DisplayConfig config = hwConfigs[c];
796 if (config == desiredConfig) {
797 return setActiveConfig(display, c);
798 }
799 }
800 return BAD_VALUE;
801}
802
Dan Stoza9e56aa02015-11-02 13:00:03 -0800803status_t SurfaceFlinger::clearAnimationFrameStats() {
804 Mutex::Autolock _l(mStateLock);
805 mAnimFrameTracker.clearStats();
806 return NO_ERROR;
807}
808
809status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
810 Mutex::Autolock _l(mStateLock);
811 mAnimFrameTracker.getStats(outStats);
812 return NO_ERROR;
813}
814
Dan Stozac4f471e2016-03-24 09:31:08 -0700815status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& /*display*/,
816 HdrCapabilities* outCapabilities) const {
817 // HWC1 does not provide HDR capabilities
818 *outCapabilities = HdrCapabilities();
819 return NO_ERROR;
820}
821
Dan Stoza9e56aa02015-11-02 13:00:03 -0800822// ----------------------------------------------------------------------------
823
824sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
825 return mEventThread->createEventConnection();
826}
827
828// ----------------------------------------------------------------------------
829
830void SurfaceFlinger::waitForEvent() {
831 mEventQueue.waitMessage();
832}
833
834void SurfaceFlinger::signalTransaction() {
835 mEventQueue.invalidate();
836}
837
838void SurfaceFlinger::signalLayerUpdate() {
839 mEventQueue.invalidate();
840}
841
842void SurfaceFlinger::signalRefresh() {
843 mEventQueue.refresh();
844}
845
846status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
847 nsecs_t reltime, uint32_t /* flags */) {
848 return mEventQueue.postMessage(msg, reltime);
849}
850
851status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
852 nsecs_t reltime, uint32_t /* flags */) {
853 status_t res = mEventQueue.postMessage(msg, reltime);
854 if (res == NO_ERROR) {
855 msg->wait();
856 }
857 return res;
858}
859
860void SurfaceFlinger::run() {
861 do {
862 waitForEvent();
863 } while (true);
864}
865
866void SurfaceFlinger::enableHardwareVsync() {
867 Mutex::Autolock _l(mHWVsyncLock);
868 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
869 mPrimaryDispSync.beginResync();
870 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
871 mEventControlThread->setVsyncEnabled(true);
872 mPrimaryHWVsyncEnabled = true;
873 }
874}
875
876void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
877 Mutex::Autolock _l(mHWVsyncLock);
878
879 if (makeAvailable) {
880 mHWVsyncAvailable = true;
881 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700882 // Hardware vsync is not currently available, so abort the resync
883 // attempt for now
Dan Stoza9e56aa02015-11-02 13:00:03 -0800884 return;
885 }
886
887 const nsecs_t period =
888 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
889
890 mPrimaryDispSync.reset();
891 mPrimaryDispSync.setPeriod(period);
892
893 if (!mPrimaryHWVsyncEnabled) {
894 mPrimaryDispSync.beginResync();
895 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
896 mEventControlThread->setVsyncEnabled(true);
897 mPrimaryHWVsyncEnabled = true;
898 }
899}
900
901void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
902 Mutex::Autolock _l(mHWVsyncLock);
903 if (mPrimaryHWVsyncEnabled) {
904 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
905 mEventControlThread->setVsyncEnabled(false);
906 mPrimaryDispSync.endResync();
907 mPrimaryHWVsyncEnabled = false;
908 }
909 if (makeUnavailable) {
910 mHWVsyncAvailable = false;
911 }
912}
913
Tim Murray4a4e4a22016-04-19 16:29:23 +0000914void SurfaceFlinger::resyncWithRateLimit() {
915 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
916 if (systemTime() - mLastSwapTime > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -0700917 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +0000918 }
919}
920
Dan Stoza9e56aa02015-11-02 13:00:03 -0800921void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
922 bool needsHwVsync = false;
923
924 { // Scope for the lock
925 Mutex::Autolock _l(mHWVsyncLock);
926 if (type == 0 && mPrimaryHWVsyncEnabled) {
927 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
928 }
929 }
930
931 if (needsHwVsync) {
932 enableHardwareVsync();
933 } else {
934 disableHardwareVsync(false);
935 }
936}
937
938void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
939 if (mEventThread == NULL) {
940 // This is a temporary workaround for b/7145521. A non-null pointer
941 // does not mean EventThread has finished initializing, so this
942 // is not a correct fix.
943 ALOGW("WARNING: EventThread not started, ignoring hotplug");
944 return;
945 }
946
947 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
948 Mutex::Autolock _l(mStateLock);
949 if (connected) {
950 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
951 } else {
952 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
953 mBuiltinDisplays[type].clear();
954 }
955 setTransactionFlags(eDisplayTransactionNeeded);
956
957 // Defer EventThread notification until SF has updated mDisplays.
958 }
959}
960
961void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
962 ATRACE_CALL();
963 getHwComposer().eventControl(disp, event, enabled);
964}
965
966void SurfaceFlinger::onMessageReceived(int32_t what) {
967 ATRACE_CALL();
968 switch (what) {
Dan Stoza9e56aa02015-11-02 13:00:03 -0800969 case MessageQueue::INVALIDATE: {
970 bool refreshNeeded = handleMessageTransaction();
971 refreshNeeded |= handleMessageInvalidate();
972 refreshNeeded |= mRepaintEverything;
973 if (refreshNeeded) {
974 // Signal a refresh if a transaction modified the window state,
975 // a new buffer was latched, or if HWC has requested a full
976 // repaint
977 signalRefresh();
978 }
979 break;
980 }
981 case MessageQueue::REFRESH: {
982 handleMessageRefresh();
983 break;
984 }
985 }
986}
987
988bool SurfaceFlinger::handleMessageTransaction() {
989 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
990 if (transactionFlags) {
991 handleTransaction(transactionFlags);
992 return true;
993 }
994 return false;
995}
996
997bool SurfaceFlinger::handleMessageInvalidate() {
998 ATRACE_CALL();
999 return handlePageFlip();
1000}
1001
1002void SurfaceFlinger::handleMessageRefresh() {
1003 ATRACE_CALL();
1004
Pablo Ceballos40845df2016-01-25 17:41:15 -08001005 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001006
Dan Stoza05dacfb2016-07-01 13:33:38 -07001007 preComposition();
1008 rebuildLayerStacks();
1009 setUpHWComposer();
1010 doDebugFlashRegions();
1011 doComposition();
1012 postComposition(refreshStartTime);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001013}
1014
1015void SurfaceFlinger::doDebugFlashRegions()
1016{
1017 // is debugging enabled
1018 if (CC_LIKELY(!mDebugRegion))
1019 return;
1020
1021 const bool repaintEverything = mRepaintEverything;
1022 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1023 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1024 if (hw->isDisplayOn()) {
1025 // transform the dirty region into this screen's coordinate space
1026 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1027 if (!dirtyRegion.isEmpty()) {
1028 // redraw the whole screen
1029 doComposeSurfaces(hw, Region(hw->bounds()));
1030
1031 // and draw the dirty region
1032 const int32_t height = hw->getHeight();
1033 RenderEngine& engine(getRenderEngine());
1034 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1035
1036 hw->compositionComplete();
1037 hw->swapBuffers(getHwComposer());
1038 }
1039 }
1040 }
1041
1042 postFramebuffer();
1043
1044 if (mDebugRegion > 1) {
1045 usleep(mDebugRegion * 1000);
1046 }
1047
1048 HWComposer& hwc(getHwComposer());
1049 if (hwc.initCheck() == NO_ERROR) {
1050 status_t err = hwc.prepare();
1051 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1052 }
1053}
1054
1055void SurfaceFlinger::preComposition()
1056{
1057 bool needExtraInvalidate = false;
1058 const LayerVector& layers(mDrawingState.layersSortedByZ);
1059 const size_t count = layers.size();
1060 for (size_t i=0 ; i<count ; i++) {
1061 if (layers[i]->onPreComposition()) {
1062 needExtraInvalidate = true;
1063 }
1064 }
1065 if (needExtraInvalidate) {
1066 signalLayerUpdate();
1067 }
1068}
1069
Pablo Ceballos40845df2016-01-25 17:41:15 -08001070void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Dan Stoza9e56aa02015-11-02 13:00:03 -08001071{
1072 const LayerVector& layers(mDrawingState.layersSortedByZ);
1073 const size_t count = layers.size();
1074 for (size_t i=0 ; i<count ; i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001075 bool frameLatched = layers[i]->onPostComposition();
1076 if (frameLatched) {
1077 recordBufferingStats(layers[i]->getName().string(),
1078 layers[i]->getOccupancyHistory(false));
1079 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08001080 }
1081
1082 const HWComposer& hwc = getHwComposer();
1083 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1084
1085 if (presentFence->isValid()) {
1086 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1087 enableHardwareVsync();
1088 } else {
1089 disableHardwareVsync(false);
1090 }
1091 }
1092
1093 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1094 if (kIgnorePresentFences) {
1095 if (hw->isDisplayOn()) {
1096 enableHardwareVsync();
1097 }
1098 }
1099
Pablo Ceballos40845df2016-01-25 17:41:15 -08001100 mFenceTracker.addFrame(refreshStartTime, presentFence,
1101 hw->getVisibleLayersSortedByZ(), hw->getClientTargetAcquireFence());
1102
Dan Stoza9e56aa02015-11-02 13:00:03 -08001103 if (mAnimCompositionPending) {
1104 mAnimCompositionPending = false;
1105
1106 if (presentFence->isValid()) {
1107 mAnimFrameTracker.setActualPresentFence(presentFence);
1108 } else {
1109 // The HWC doesn't support present fences, so use the refresh
1110 // timestamp instead.
1111 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1112 mAnimFrameTracker.setActualPresentTime(presentTime);
1113 }
1114 mAnimFrameTracker.advanceFrame();
1115 }
1116
1117 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1118 return;
1119 }
1120
1121 nsecs_t currentTime = systemTime();
1122 if (mHasPoweredOff) {
1123 mHasPoweredOff = false;
1124 } else {
1125 nsecs_t period = mPrimaryDispSync.getPeriod();
1126 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1127 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1128 if (numPeriods < NUM_BUCKETS - 1) {
1129 mFrameBuckets[numPeriods] += elapsedTime;
1130 } else {
1131 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1132 }
1133 mTotalTime += elapsedTime;
1134 }
1135 mLastSwapTime = currentTime;
1136}
1137
1138void SurfaceFlinger::rebuildLayerStacks() {
1139 // rebuild the visible layer list per screen
1140 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1141 ATRACE_CALL();
1142 mVisibleRegionsDirty = false;
1143 invalidateHwcGeometry();
1144
1145 const LayerVector& layers(mDrawingState.layersSortedByZ);
1146 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1147 Region opaqueRegion;
1148 Region dirtyRegion;
1149 Vector< sp<Layer> > layersSortedByZ;
1150 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1151 const Transform& tr(hw->getTransform());
1152 const Rect bounds(hw->getBounds());
1153 if (hw->isDisplayOn()) {
1154 SurfaceFlinger::computeVisibleRegions(layers,
1155 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1156
1157 const size_t count = layers.size();
1158 for (size_t i=0 ; i<count ; i++) {
1159 const sp<Layer>& layer(layers[i]);
1160 const Layer::State& s(layer->getDrawingState());
1161 if (s.layerStack == hw->getLayerStack()) {
1162 Region drawRegion(tr.transform(
1163 layer->visibleNonTransparentRegion));
1164 drawRegion.andSelf(bounds);
1165 if (!drawRegion.isEmpty()) {
1166 layersSortedByZ.add(layer);
1167 }
1168 }
1169 }
1170 }
1171 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1172 hw->undefinedRegion.set(bounds);
1173 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1174 hw->dirtyRegion.orSelf(dirtyRegion);
1175 }
1176 }
1177}
1178
1179void SurfaceFlinger::setUpHWComposer() {
1180 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1181 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1182 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1183 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1184
1185 // If nothing has changed (!dirty), don't recompose.
1186 // If something changed, but we don't currently have any visible layers,
1187 // and didn't when we last did a composition, then skip it this time.
1188 // The second rule does two things:
1189 // - When all layers are removed from a display, we'll emit one black
1190 // frame, then nothing more until we get new layers.
1191 // - When a display is created with a private layer stack, we won't
1192 // emit any black frames until a layer is added to the layer stack.
1193 bool mustRecompose = dirty && !(empty && wasEmpty);
1194
1195 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1196 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1197 mustRecompose ? "doing" : "skipping",
1198 dirty ? "+" : "-",
1199 empty ? "+" : "-",
1200 wasEmpty ? "+" : "-");
1201
1202 mDisplays[dpy]->beginFrame(mustRecompose);
1203
1204 if (mustRecompose) {
1205 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1206 }
1207 }
1208
1209 HWComposer& hwc(getHwComposer());
1210 if (hwc.initCheck() == NO_ERROR) {
1211 // build the h/w work list
1212 if (CC_UNLIKELY(mHwWorkListDirty)) {
1213 mHwWorkListDirty = false;
1214 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1215 sp<const DisplayDevice> hw(mDisplays[dpy]);
1216 const int32_t id = hw->getHwcDisplayId();
1217 if (id >= 0) {
1218 const Vector< sp<Layer> >& currentLayers(
1219 hw->getVisibleLayersSortedByZ());
1220 const size_t count = currentLayers.size();
1221 if (hwc.createWorkList(id, count) == NO_ERROR) {
1222 HWComposer::LayerListIterator cur = hwc.begin(id);
1223 const HWComposer::LayerListIterator end = hwc.end(id);
1224 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1225 const sp<Layer>& layer(currentLayers[i]);
1226 layer->setGeometry(hw, *cur);
1227 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1228 cur->setSkip(true);
1229 }
1230 }
1231 }
1232 }
1233 }
1234 }
1235
1236 // set the per-frame data
1237 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1238 sp<const DisplayDevice> hw(mDisplays[dpy]);
1239 const int32_t id = hw->getHwcDisplayId();
1240 if (id >= 0) {
1241 const Vector< sp<Layer> >& currentLayers(
1242 hw->getVisibleLayersSortedByZ());
1243 const size_t count = currentLayers.size();
1244 HWComposer::LayerListIterator cur = hwc.begin(id);
1245 const HWComposer::LayerListIterator end = hwc.end(id);
1246 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1247 /*
1248 * update the per-frame h/w composer data for each layer
1249 * and build the transparent region of the FB
1250 */
1251 const sp<Layer>& layer(currentLayers[i]);
1252 layer->setPerFrameData(hw, *cur);
1253 }
1254 }
1255 }
1256
1257 // If possible, attempt to use the cursor overlay on each display.
1258 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1259 sp<const DisplayDevice> hw(mDisplays[dpy]);
1260 const int32_t id = hw->getHwcDisplayId();
1261 if (id >= 0) {
1262 const Vector< sp<Layer> >& currentLayers(
1263 hw->getVisibleLayersSortedByZ());
1264 const size_t count = currentLayers.size();
1265 HWComposer::LayerListIterator cur = hwc.begin(id);
1266 const HWComposer::LayerListIterator end = hwc.end(id);
1267 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1268 const sp<Layer>& layer(currentLayers[i]);
1269 if (layer->isPotentialCursor()) {
1270 cur->setIsCursorLayerHint();
1271 break;
1272 }
1273 }
1274 }
1275 }
1276
1277 status_t err = hwc.prepare();
1278 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1279
1280 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1281 sp<const DisplayDevice> hw(mDisplays[dpy]);
1282 hw->prepareFrame(hwc);
1283 }
1284 }
1285}
1286
1287void SurfaceFlinger::doComposition() {
1288 ATRACE_CALL();
1289 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1290 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1291 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1292 if (hw->isDisplayOn()) {
1293 // transform the dirty region into this screen's coordinate space
1294 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1295
1296 // repaint the framebuffer (if needed)
1297 doDisplayComposition(hw, dirtyRegion);
1298
1299 hw->dirtyRegion.clear();
1300 hw->flip(hw->swapRegion);
1301 hw->swapRegion.clear();
1302 }
1303 // inform the h/w that we're done compositing
1304 hw->compositionComplete();
1305 }
1306 postFramebuffer();
1307}
1308
1309void SurfaceFlinger::postFramebuffer()
1310{
1311 ATRACE_CALL();
1312
1313 const nsecs_t now = systemTime();
1314 mDebugInSwapBuffers = now;
1315
1316 HWComposer& hwc(getHwComposer());
1317 if (hwc.initCheck() == NO_ERROR) {
1318 if (!hwc.supportsFramebufferTarget()) {
1319 // EGL spec says:
1320 // "surface must be bound to the calling thread's current context,
1321 // for the current rendering API."
1322 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1323 }
1324 hwc.commit();
1325 }
1326
1327 // make the default display current because the VirtualDisplayDevice code cannot
1328 // deal with dequeueBuffer() being called outside of the composition loop; however
1329 // the code below can call glFlush() which is allowed (and does in some case) call
1330 // dequeueBuffer().
1331 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1332
1333 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1334 sp<const DisplayDevice> hw(mDisplays[dpy]);
1335 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1336 hw->onSwapBuffersCompleted(hwc);
1337 const size_t count = currentLayers.size();
1338 int32_t id = hw->getHwcDisplayId();
1339 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1340 HWComposer::LayerListIterator cur = hwc.begin(id);
1341 const HWComposer::LayerListIterator end = hwc.end(id);
1342 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1343 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1344 }
1345 } else {
1346 for (size_t i = 0; i < count; i++) {
1347 currentLayers[i]->onLayerDisplayed(hw, NULL);
1348 }
1349 }
1350 }
1351
1352 mLastSwapBufferTime = systemTime() - now;
1353 mDebugInSwapBuffers = 0;
1354
1355 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1356 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1357 logFrameStats();
1358 }
1359}
1360
1361void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1362{
1363 ATRACE_CALL();
1364
1365 // here we keep a copy of the drawing state (that is the state that's
1366 // going to be overwritten by handleTransactionLocked()) outside of
1367 // mStateLock so that the side-effects of the State assignment
1368 // don't happen with mStateLock held (which can cause deadlocks).
1369 State drawingState(mDrawingState);
1370
1371 Mutex::Autolock _l(mStateLock);
1372 const nsecs_t now = systemTime();
1373 mDebugInTransaction = now;
1374
1375 // Here we're guaranteed that some transaction flags are set
1376 // so we can call handleTransactionLocked() unconditionally.
1377 // We call getTransactionFlags(), which will also clear the flags,
1378 // with mStateLock held to guarantee that mCurrentState won't change
1379 // until the transaction is committed.
1380
1381 transactionFlags = getTransactionFlags(eTransactionMask);
1382 handleTransactionLocked(transactionFlags);
1383
1384 mLastTransactionTime = systemTime() - now;
1385 mDebugInTransaction = 0;
1386 invalidateHwcGeometry();
1387 // here the transaction has been committed
1388}
1389
1390void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1391{
1392 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1393 const size_t count = currentLayers.size();
1394
1395 // Notify all layers of available frames
1396 for (size_t i = 0; i < count; ++i) {
1397 currentLayers[i]->notifyAvailableFrames();
1398 }
1399
1400 /*
1401 * Traversal of the children
1402 * (perform the transaction for each of them if needed)
1403 */
1404
1405 if (transactionFlags & eTraversalNeeded) {
1406 for (size_t i=0 ; i<count ; i++) {
1407 const sp<Layer>& layer(currentLayers[i]);
1408 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1409 if (!trFlags) continue;
1410
1411 const uint32_t flags = layer->doTransaction(0);
1412 if (flags & Layer::eVisibleRegion)
1413 mVisibleRegionsDirty = true;
1414 }
1415 }
1416
1417 /*
1418 * Perform display own transactions if needed
1419 */
1420
1421 if (transactionFlags & eDisplayTransactionNeeded) {
1422 // here we take advantage of Vector's copy-on-write semantics to
1423 // improve performance by skipping the transaction entirely when
1424 // know that the lists are identical
1425 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1426 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1427 if (!curr.isIdenticalTo(draw)) {
1428 mVisibleRegionsDirty = true;
1429 const size_t cc = curr.size();
1430 size_t dc = draw.size();
1431
1432 // find the displays that were removed
1433 // (ie: in drawing state but not in current state)
1434 // also handle displays that changed
1435 // (ie: displays that are in both lists)
1436 for (size_t i=0 ; i<dc ; i++) {
1437 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1438 if (j < 0) {
1439 // in drawing state but not in current state
1440 if (!draw[i].isMainDisplay()) {
1441 // Call makeCurrent() on the primary display so we can
1442 // be sure that nothing associated with this display
1443 // is current.
1444 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1445 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1446 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1447 if (hw != NULL)
1448 hw->disconnect(getHwComposer());
1449 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1450 mEventThread->onHotplugReceived(draw[i].type, false);
1451 mDisplays.removeItem(draw.keyAt(i));
1452 } else {
1453 ALOGW("trying to remove the main display");
1454 }
1455 } else {
1456 // this display is in both lists. see if something changed.
1457 const DisplayDeviceState& state(curr[j]);
1458 const wp<IBinder>& display(curr.keyAt(j));
1459 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1460 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1461 if (state_binder != draw_binder) {
1462 // changing the surface is like destroying and
1463 // recreating the DisplayDevice, so we just remove it
1464 // from the drawing state, so that it get re-added
1465 // below.
1466 sp<DisplayDevice> hw(getDisplayDevice(display));
1467 if (hw != NULL)
1468 hw->disconnect(getHwComposer());
1469 mDisplays.removeItem(display);
1470 mDrawingState.displays.removeItemsAt(i);
1471 dc--; i--;
1472 // at this point we must loop to the next item
1473 continue;
1474 }
1475
1476 const sp<DisplayDevice> disp(getDisplayDevice(display));
1477 if (disp != NULL) {
1478 if (state.layerStack != draw[i].layerStack) {
1479 disp->setLayerStack(state.layerStack);
1480 }
1481 if ((state.orientation != draw[i].orientation)
1482 || (state.viewport != draw[i].viewport)
1483 || (state.frame != draw[i].frame))
1484 {
1485 disp->setProjection(state.orientation,
1486 state.viewport, state.frame);
1487 }
1488 if (state.width != draw[i].width || state.height != draw[i].height) {
1489 disp->setDisplaySize(state.width, state.height);
1490 }
1491 }
1492 }
1493 }
1494
1495 // find displays that were added
1496 // (ie: in current state but not in drawing state)
1497 for (size_t i=0 ; i<cc ; i++) {
1498 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1499 const DisplayDeviceState& state(curr[i]);
1500
1501 sp<DisplaySurface> dispSurface;
1502 sp<IGraphicBufferProducer> producer;
1503 sp<IGraphicBufferProducer> bqProducer;
1504 sp<IGraphicBufferConsumer> bqConsumer;
1505 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1506 new GraphicBufferAlloc());
1507
1508 int32_t hwcDisplayId = -1;
1509 if (state.isVirtualDisplay()) {
1510 // Virtual displays without a surface are dormant:
1511 // they have external state (layer stack, projection,
1512 // etc.) but no internal state (i.e. a DisplayDevice).
1513 if (state.surface != NULL) {
1514
1515 int width = 0;
1516 int status = state.surface->query(
1517 NATIVE_WINDOW_WIDTH, &width);
1518 ALOGE_IF(status != NO_ERROR,
1519 "Unable to query width (%d)", status);
1520 int height = 0;
1521 status = state.surface->query(
1522 NATIVE_WINDOW_HEIGHT, &height);
1523 ALOGE_IF(status != NO_ERROR,
1524 "Unable to query height (%d)", status);
1525 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1526 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1527 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1528 hwcDisplayId = allocateHwcDisplayId(state.type);
1529 }
1530
1531 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1532 *mHwc, hwcDisplayId, state.surface,
1533 bqProducer, bqConsumer, state.displayName);
1534
1535 dispSurface = vds;
1536 producer = vds;
1537 }
1538 } else {
1539 ALOGE_IF(state.surface!=NULL,
1540 "adding a supported display, but rendering "
1541 "surface is provided (%p), ignoring it",
1542 state.surface.get());
1543 hwcDisplayId = allocateHwcDisplayId(state.type);
1544 // for supported (by hwc) displays we provide our
1545 // own rendering surface
1546 dispSurface = new FramebufferSurface(*mHwc, state.type,
1547 bqConsumer);
1548 producer = bqProducer;
1549 }
1550
1551 const wp<IBinder>& display(curr.keyAt(i));
1552 if (dispSurface != NULL) {
1553 sp<DisplayDevice> hw = new DisplayDevice(this,
1554 state.type, hwcDisplayId,
1555 mHwc->getFormat(hwcDisplayId), state.isSecure,
1556 display, dispSurface, producer,
1557 mRenderEngine->getEGLConfig());
1558 hw->setLayerStack(state.layerStack);
1559 hw->setProjection(state.orientation,
1560 state.viewport, state.frame);
1561 hw->setDisplayName(state.displayName);
1562 mDisplays.add(display, hw);
1563 if (state.isVirtualDisplay()) {
1564 if (hwcDisplayId >= 0) {
1565 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1566 hw->getWidth(), hw->getHeight(),
1567 hw->getFormat());
1568 }
1569 } else {
1570 mEventThread->onHotplugReceived(state.type, true);
1571 }
1572 }
1573 }
1574 }
1575 }
1576 }
1577
1578 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1579 // The transform hint might have changed for some layers
1580 // (either because a display has changed, or because a layer
1581 // as changed).
1582 //
1583 // Walk through all the layers in currentLayers,
1584 // and update their transform hint.
1585 //
1586 // If a layer is visible only on a single display, then that
1587 // display is used to calculate the hint, otherwise we use the
1588 // default display.
1589 //
1590 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1591 // the hint is set before we acquire a buffer from the surface texture.
1592 //
1593 // NOTE: layer transactions have taken place already, so we use their
1594 // drawing state. However, SurfaceFlinger's own transaction has not
1595 // happened yet, so we must use the current state layer list
1596 // (soon to become the drawing state list).
1597 //
1598 sp<const DisplayDevice> disp;
1599 uint32_t currentlayerStack = 0;
1600 for (size_t i=0; i<count; i++) {
1601 // NOTE: we rely on the fact that layers are sorted by
1602 // layerStack first (so we don't have to traverse the list
1603 // of displays for every layer).
1604 const sp<Layer>& layer(currentLayers[i]);
1605 uint32_t layerStack = layer->getDrawingState().layerStack;
1606 if (i==0 || currentlayerStack != layerStack) {
1607 currentlayerStack = layerStack;
1608 // figure out if this layerstack is mirrored
1609 // (more than one display) if so, pick the default display,
1610 // if not, pick the only display it's on.
1611 disp.clear();
1612 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1613 sp<const DisplayDevice> hw(mDisplays[dpy]);
1614 if (hw->getLayerStack() == currentlayerStack) {
1615 if (disp == NULL) {
1616 disp = hw;
1617 } else {
1618 disp = NULL;
1619 break;
1620 }
1621 }
1622 }
1623 }
1624 if (disp == NULL) {
1625 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1626 // redraw after transform hint changes. See bug 8508397.
1627
1628 // could be null when this layer is using a layerStack
1629 // that is not visible on any display. Also can occur at
1630 // screen off/on times.
1631 disp = getDefaultDisplayDevice();
1632 }
1633 layer->updateTransformHint(disp);
1634 }
1635 }
1636
1637
1638 /*
1639 * Perform our own transaction if needed
1640 */
1641
1642 const LayerVector& layers(mDrawingState.layersSortedByZ);
1643 if (currentLayers.size() > layers.size()) {
1644 // layers have been added
1645 mVisibleRegionsDirty = true;
1646 }
1647
1648 // some layers might have been removed, so
1649 // we need to update the regions they're exposing.
1650 if (mLayersRemoved) {
1651 mLayersRemoved = false;
1652 mVisibleRegionsDirty = true;
1653 const size_t count = layers.size();
1654 for (size_t i=0 ; i<count ; i++) {
1655 const sp<Layer>& layer(layers[i]);
1656 if (currentLayers.indexOf(layer) < 0) {
1657 // this layer is not visible anymore
1658 // TODO: we could traverse the tree from front to back and
1659 // compute the actual visible region
1660 // TODO: we could cache the transformed region
1661 const Layer::State& s(layer->getDrawingState());
Robert Carr3dcabfa2016-03-01 18:36:58 -08001662 Region visibleReg = s.active.transform.transform(
Dan Stoza9e56aa02015-11-02 13:00:03 -08001663 Region(Rect(s.active.w, s.active.h)));
1664 invalidateLayerStack(s.layerStack, visibleReg);
1665 }
1666 }
1667 }
1668
1669 commitTransaction();
1670
1671 updateCursorAsync();
1672}
1673
1674void SurfaceFlinger::updateCursorAsync()
1675{
1676 HWComposer& hwc(getHwComposer());
1677 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1678 sp<const DisplayDevice> hw(mDisplays[dpy]);
1679 const int32_t id = hw->getHwcDisplayId();
1680 if (id < 0) {
1681 continue;
1682 }
1683 const Vector< sp<Layer> >& currentLayers(
1684 hw->getVisibleLayersSortedByZ());
1685 const size_t count = currentLayers.size();
1686 HWComposer::LayerListIterator cur = hwc.begin(id);
1687 const HWComposer::LayerListIterator end = hwc.end(id);
1688 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1689 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1690 continue;
1691 }
1692 const sp<Layer>& layer(currentLayers[i]);
1693 Rect cursorPos = layer->getPosition(hw);
1694 hwc.setCursorPositionAsync(id, cursorPos);
1695 break;
1696 }
1697 }
1698}
1699
1700void SurfaceFlinger::commitTransaction()
1701{
1702 if (!mLayersPendingRemoval.isEmpty()) {
1703 // Notify removed layers now that they can't be drawn from
1704 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
Dan Stozae77c7662016-05-13 11:37:28 -07001705 recordBufferingStats(mLayersPendingRemoval[i]->getName().string(),
1706 mLayersPendingRemoval[i]->getOccupancyHistory(true));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001707 mLayersPendingRemoval[i]->onRemoved();
1708 }
1709 mLayersPendingRemoval.clear();
1710 }
1711
1712 // If this transaction is part of a window animation then the next frame
1713 // we composite should be considered an animation as well.
1714 mAnimCompositionPending = mAnimTransactionPending;
1715
1716 mDrawingState = mCurrentState;
1717 mTransactionPending = false;
1718 mAnimTransactionPending = false;
1719 mTransactionCV.broadcast();
1720}
1721
1722void SurfaceFlinger::computeVisibleRegions(
1723 const LayerVector& currentLayers, uint32_t layerStack,
1724 Region& outDirtyRegion, Region& outOpaqueRegion)
1725{
1726 ATRACE_CALL();
1727
1728 Region aboveOpaqueLayers;
1729 Region aboveCoveredLayers;
1730 Region dirty;
1731
1732 outDirtyRegion.clear();
1733
1734 size_t i = currentLayers.size();
1735 while (i--) {
1736 const sp<Layer>& layer = currentLayers[i];
1737
1738 // start with the whole surface at its current location
1739 const Layer::State& s(layer->getDrawingState());
1740
1741 // only consider the layers on the given layer stack
1742 if (s.layerStack != layerStack)
1743 continue;
1744
1745 /*
1746 * opaqueRegion: area of a surface that is fully opaque.
1747 */
1748 Region opaqueRegion;
1749
1750 /*
1751 * visibleRegion: area of a surface that is visible on screen
1752 * and not fully transparent. This is essentially the layer's
1753 * footprint minus the opaque regions above it.
1754 * Areas covered by a translucent surface are considered visible.
1755 */
1756 Region visibleRegion;
1757
1758 /*
1759 * coveredRegion: area of a surface that is covered by all
1760 * visible regions above it (which includes the translucent areas).
1761 */
1762 Region coveredRegion;
1763
1764 /*
1765 * transparentRegion: area of a surface that is hinted to be completely
1766 * transparent. This is only used to tell when the layer has no visible
1767 * non-transparent regions and can be removed from the layer list. It
1768 * does not affect the visibleRegion of this layer or any layers
1769 * beneath it. The hint may not be correct if apps don't respect the
1770 * SurfaceView restrictions (which, sadly, some don't).
1771 */
1772 Region transparentRegion;
1773
1774
1775 // handle hidden surfaces by setting the visible region to empty
1776 if (CC_LIKELY(layer->isVisible())) {
1777 const bool translucent = !layer->isOpaque(s);
Robert Carr3dcabfa2016-03-01 18:36:58 -08001778 Rect bounds(s.active.transform.transform(layer->computeBounds()));
Dan Stoza9e56aa02015-11-02 13:00:03 -08001779 visibleRegion.set(bounds);
1780 if (!visibleRegion.isEmpty()) {
1781 // Remove the transparent area from the visible region
1782 if (translucent) {
Robert Carr3dcabfa2016-03-01 18:36:58 -08001783 const Transform tr(s.active.transform);
Dan Stoza22f7fc42016-05-10 16:19:53 -07001784 if (tr.preserveRects()) {
1785 // transform the transparent region
1786 transparentRegion = tr.transform(s.activeTransparentRegion);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001787 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07001788 // transformation too complex, can't do the
1789 // transparent region optimization.
1790 transparentRegion.clear();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001791 }
1792 }
1793
1794 // compute the opaque region
Robert Carr3dcabfa2016-03-01 18:36:58 -08001795 const int32_t layerOrientation = s.active.transform.getOrientation();
Dan Stoza9e56aa02015-11-02 13:00:03 -08001796 if (s.alpha==255 && !translucent &&
1797 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1798 // the opaque region is the layer's footprint
1799 opaqueRegion = visibleRegion;
1800 }
1801 }
1802 }
1803
1804 // Clip the covered region to the visible region
1805 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1806
1807 // Update aboveCoveredLayers for next (lower) layer
1808 aboveCoveredLayers.orSelf(visibleRegion);
1809
1810 // subtract the opaque region covered by the layers above us
1811 visibleRegion.subtractSelf(aboveOpaqueLayers);
1812
1813 // compute this layer's dirty region
1814 if (layer->contentDirty) {
1815 // we need to invalidate the whole region
1816 dirty = visibleRegion;
1817 // as well, as the old visible region
1818 dirty.orSelf(layer->visibleRegion);
1819 layer->contentDirty = false;
1820 } else {
1821 /* compute the exposed region:
1822 * the exposed region consists of two components:
1823 * 1) what's VISIBLE now and was COVERED before
1824 * 2) what's EXPOSED now less what was EXPOSED before
1825 *
1826 * note that (1) is conservative, we start with the whole
1827 * visible region but only keep what used to be covered by
1828 * something -- which mean it may have been exposed.
1829 *
1830 * (2) handles areas that were not covered by anything but got
1831 * exposed because of a resize.
1832 */
1833 const Region newExposed = visibleRegion - coveredRegion;
1834 const Region oldVisibleRegion = layer->visibleRegion;
1835 const Region oldCoveredRegion = layer->coveredRegion;
1836 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1837 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1838 }
1839 dirty.subtractSelf(aboveOpaqueLayers);
1840
1841 // accumulate to the screen dirty region
1842 outDirtyRegion.orSelf(dirty);
1843
1844 // Update aboveOpaqueLayers for next (lower) layer
1845 aboveOpaqueLayers.orSelf(opaqueRegion);
1846
1847 // Store the visible region in screen space
1848 layer->setVisibleRegion(visibleRegion);
1849 layer->setCoveredRegion(coveredRegion);
1850 layer->setVisibleNonTransparentRegion(
1851 visibleRegion.subtract(transparentRegion));
1852 }
1853
1854 outOpaqueRegion = aboveOpaqueLayers;
1855}
1856
1857void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1858 const Region& dirty) {
1859 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1860 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1861 if (hw->getLayerStack() == layerStack) {
1862 hw->dirtyRegion.orSelf(dirty);
1863 }
1864 }
1865}
1866
1867bool SurfaceFlinger::handlePageFlip()
1868{
1869 Region dirtyRegion;
1870
1871 bool visibleRegions = false;
1872 const LayerVector& layers(mDrawingState.layersSortedByZ);
1873 bool frameQueued = false;
1874
1875 // Store the set of layers that need updates. This set must not change as
1876 // buffers are being latched, as this could result in a deadlock.
1877 // Example: Two producers share the same command stream and:
1878 // 1.) Layer 0 is latched
1879 // 2.) Layer 0 gets a new frame
1880 // 2.) Layer 1 gets a new frame
1881 // 3.) Layer 1 is latched.
1882 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1883 // second frame. But layer 0's second frame could be waiting on display.
1884 Vector<Layer*> layersWithQueuedFrames;
1885 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1886 const sp<Layer>& layer(layers[i]);
1887 if (layer->hasQueuedFrame()) {
1888 frameQueued = true;
1889 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1890 layersWithQueuedFrames.push_back(layer.get());
1891 } else {
1892 layer->useEmptyDamage();
1893 }
1894 } else {
1895 layer->useEmptyDamage();
1896 }
1897 }
1898 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1899 Layer* layer = layersWithQueuedFrames[i];
1900 const Region dirty(layer->latchBuffer(visibleRegions));
1901 layer->useSurfaceDamage();
1902 const Layer::State& s(layer->getDrawingState());
1903 invalidateLayerStack(s.layerStack, dirty);
1904 }
1905
1906 mVisibleRegionsDirty |= visibleRegions;
1907
1908 // If we will need to wake up at some time in the future to deal with a
1909 // queued frame that shouldn't be displayed during this vsync period, wake
1910 // up during the next vsync period to check again.
1911 if (frameQueued && layersWithQueuedFrames.empty()) {
1912 signalLayerUpdate();
1913 }
1914
1915 // Only continue with the refresh if there is actually new work to do
1916 return !layersWithQueuedFrames.empty();
1917}
1918
1919void SurfaceFlinger::invalidateHwcGeometry()
1920{
1921 mHwWorkListDirty = true;
1922}
1923
1924
1925void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1926 const Region& inDirtyRegion)
1927{
1928 // We only need to actually compose the display if:
1929 // 1) It is being handled by hardware composer, which may need this to
1930 // keep its virtual display state machine in sync, or
1931 // 2) There is work to be done (the dirty region isn't empty)
1932 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1933 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1934 return;
1935 }
1936
1937 Region dirtyRegion(inDirtyRegion);
1938
1939 // compute the invalid region
1940 hw->swapRegion.orSelf(dirtyRegion);
1941
1942 uint32_t flags = hw->getFlags();
1943 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1944 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1945 // takes a rectangle, we must make sure to update that whole
1946 // rectangle in that case
1947 dirtyRegion.set(hw->swapRegion.bounds());
1948 } else {
1949 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1950 // We need to redraw the rectangle that will be updated
1951 // (pushed to the framebuffer).
1952 // This is needed because PARTIAL_UPDATES only takes one
1953 // rectangle instead of a region (see DisplayDevice::flip())
1954 dirtyRegion.set(hw->swapRegion.bounds());
1955 } else {
1956 // we need to redraw everything (the whole screen)
1957 dirtyRegion.set(hw->bounds());
1958 hw->swapRegion = dirtyRegion;
1959 }
1960 }
1961
1962 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1963 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1964 } else {
1965 RenderEngine& engine(getRenderEngine());
1966 mat4 colorMatrix = mColorMatrix;
1967 if (mDaltonize) {
1968 colorMatrix = colorMatrix * mDaltonizer();
1969 }
1970 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1971 doComposeSurfaces(hw, dirtyRegion);
1972 engine.setupColorTransform(oldMatrix);
1973 }
1974
1975 // update the swap region and clear the dirty region
1976 hw->swapRegion.orSelf(dirtyRegion);
1977
1978 // swap buffers (presentation)
1979 hw->swapBuffers(getHwComposer());
1980}
1981
1982bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1983{
1984 RenderEngine& engine(getRenderEngine());
1985 const int32_t id = hw->getHwcDisplayId();
1986 HWComposer& hwc(getHwComposer());
1987 HWComposer::LayerListIterator cur = hwc.begin(id);
1988 const HWComposer::LayerListIterator end = hwc.end(id);
1989
1990 bool hasGlesComposition = hwc.hasGlesComposition(id);
1991 if (hasGlesComposition) {
1992 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1993 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1994 hw->getDisplayName().string());
1995 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1996 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1997 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1998 }
1999 return false;
2000 }
2001
2002 // Never touch the framebuffer if we don't have any framebuffer layers
2003 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2004 if (hasHwcComposition) {
2005 // when using overlays, we assume a fully transparent framebuffer
2006 // NOTE: we could reduce how much we need to clear, for instance
2007 // remove where there are opaque FB layers. however, on some
2008 // GPUs doing a "clean slate" clear might be more efficient.
2009 // We'll revisit later if needed.
2010 engine.clearWithColor(0, 0, 0, 0);
2011 } else {
2012 // we start with the whole screen area
2013 const Region bounds(hw->getBounds());
2014
2015 // we remove the scissor part
2016 // we're left with the letterbox region
2017 // (common case is that letterbox ends-up being empty)
2018 const Region letterbox(bounds.subtract(hw->getScissor()));
2019
2020 // compute the area to clear
2021 Region region(hw->undefinedRegion.merge(letterbox));
2022
2023 // but limit it to the dirty region
2024 region.andSelf(dirty);
2025
2026 // screen is already cleared here
2027 if (!region.isEmpty()) {
2028 // can happen with SurfaceView
2029 drawWormhole(hw, region);
2030 }
2031 }
2032
2033 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2034 // just to be on the safe side, we don't set the
2035 // scissor on the main display. It should never be needed
2036 // anyways (though in theory it could since the API allows it).
2037 const Rect& bounds(hw->getBounds());
2038 const Rect& scissor(hw->getScissor());
2039 if (scissor != bounds) {
2040 // scissor doesn't match the screen's dimensions, so we
2041 // need to clear everything outside of it and enable
2042 // the GL scissor so we don't draw anything where we shouldn't
2043
2044 // enable scissor for this frame
2045 const uint32_t height = hw->getHeight();
2046 engine.setScissor(scissor.left, height - scissor.bottom,
2047 scissor.getWidth(), scissor.getHeight());
2048 }
2049 }
2050 }
2051
2052 /*
2053 * and then, render the layers targeted at the framebuffer
2054 */
2055
2056 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2057 const size_t count = layers.size();
2058 const Transform& tr = hw->getTransform();
2059 if (cur != end) {
2060 // we're using h/w composer
2061 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2062 const sp<Layer>& layer(layers[i]);
2063 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2064 if (!clip.isEmpty()) {
2065 switch (cur->getCompositionType()) {
2066 case HWC_CURSOR_OVERLAY:
2067 case HWC_OVERLAY: {
2068 const Layer::State& state(layer->getDrawingState());
2069 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2070 && i
2071 && layer->isOpaque(state) && (state.alpha == 0xFF)
2072 && hasGlesComposition) {
2073 // never clear the very first layer since we're
2074 // guaranteed the FB is already cleared
2075 layer->clearWithOpenGL(hw, clip);
2076 }
2077 break;
2078 }
2079 case HWC_FRAMEBUFFER: {
2080 layer->draw(hw, clip);
2081 break;
2082 }
2083 case HWC_FRAMEBUFFER_TARGET: {
2084 // this should not happen as the iterator shouldn't
2085 // let us get there.
2086 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2087 break;
2088 }
2089 }
2090 }
2091 layer->setAcquireFence(hw, *cur);
2092 }
2093 } else {
2094 // we're not using h/w composer
2095 for (size_t i=0 ; i<count ; ++i) {
2096 const sp<Layer>& layer(layers[i]);
2097 const Region clip(dirty.intersect(
2098 tr.transform(layer->visibleRegion)));
2099 if (!clip.isEmpty()) {
2100 layer->draw(hw, clip);
2101 }
2102 }
2103 }
2104
2105 // disable scissor at the end of the frame
2106 engine.disableScissor();
2107 return true;
2108}
2109
2110void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2111 const int32_t height = hw->getHeight();
2112 RenderEngine& engine(getRenderEngine());
2113 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2114}
2115
2116status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2117 const sp<IBinder>& handle,
2118 const sp<IGraphicBufferProducer>& gbc,
2119 const sp<Layer>& lbc)
2120{
2121 // add this layer to the current state list
2122 {
2123 Mutex::Autolock _l(mStateLock);
2124 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2125 return NO_MEMORY;
2126 }
2127 mCurrentState.layersSortedByZ.add(lbc);
2128 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2129 }
2130
2131 // attach this layer to the client
2132 client->attachLayer(handle, lbc);
2133
2134 return NO_ERROR;
2135}
2136
2137status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2138 Mutex::Autolock _l(mStateLock);
2139 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2140 if (index >= 0) {
2141 mLayersPendingRemoval.push(layer);
2142 mLayersRemoved = true;
2143 setTransactionFlags(eTransactionNeeded);
2144 return NO_ERROR;
2145 }
2146 return status_t(index);
2147}
2148
2149uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2150 return android_atomic_release_load(&mTransactionFlags);
2151}
2152
2153uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2154 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2155}
2156
2157uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2158 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2159 if ((old & flags)==0) { // wake the server up
2160 signalTransaction();
2161 }
2162 return old;
2163}
2164
2165void SurfaceFlinger::setTransactionState(
2166 const Vector<ComposerState>& state,
2167 const Vector<DisplayState>& displays,
2168 uint32_t flags)
2169{
2170 ATRACE_CALL();
2171 Mutex::Autolock _l(mStateLock);
2172 uint32_t transactionFlags = 0;
2173
2174 if (flags & eAnimation) {
2175 // For window updates that are part of an animation we must wait for
2176 // previous animation "frames" to be handled.
2177 while (mAnimTransactionPending) {
2178 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2179 if (CC_UNLIKELY(err != NO_ERROR)) {
2180 // just in case something goes wrong in SF, return to the
2181 // caller after a few seconds.
2182 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2183 "waiting for previous animation frame");
2184 mAnimTransactionPending = false;
2185 break;
2186 }
2187 }
2188 }
2189
2190 size_t count = displays.size();
2191 for (size_t i=0 ; i<count ; i++) {
2192 const DisplayState& s(displays[i]);
2193 transactionFlags |= setDisplayStateLocked(s);
2194 }
2195
2196 count = state.size();
2197 for (size_t i=0 ; i<count ; i++) {
2198 const ComposerState& s(state[i]);
2199 // Here we need to check that the interface we're given is indeed
2200 // one of our own. A malicious client could give us a NULL
2201 // IInterface, or one of its own or even one of our own but a
2202 // different type. All these situations would cause us to crash.
2203 //
2204 // NOTE: it would be better to use RTTI as we could directly check
2205 // that we have a Client*. however, RTTI is disabled in Android.
2206 if (s.client != NULL) {
2207 sp<IBinder> binder = IInterface::asBinder(s.client);
2208 if (binder != NULL) {
2209 String16 desc(binder->getInterfaceDescriptor());
2210 if (desc == ISurfaceComposerClient::descriptor) {
2211 sp<Client> client( static_cast<Client *>(s.client.get()) );
2212 transactionFlags |= setClientStateLocked(client, s.state);
2213 }
2214 }
2215 }
2216 }
2217
Robert Carr2a7dbb42016-05-24 11:41:28 -07002218 // If a synchronous transaction is explicitly requested without any changes,
2219 // force a transaction anyway. This can be used as a flush mechanism for
2220 // previous async transactions.
2221 if (transactionFlags == 0 && (flags & eSynchronous)) {
2222 transactionFlags = eTransactionNeeded;
2223 }
2224
Dan Stoza9e56aa02015-11-02 13:00:03 -08002225 if (transactionFlags) {
Irvel468051e2016-06-13 16:44:44 -07002226 mInterceptor.saveLayerUpdates(state, flags);
2227
Dan Stoza9e56aa02015-11-02 13:00:03 -08002228 // this triggers the transaction
2229 setTransactionFlags(transactionFlags);
2230
2231 // if this is a synchronous transaction, wait for it to take effect
2232 // before returning.
2233 if (flags & eSynchronous) {
2234 mTransactionPending = true;
2235 }
2236 if (flags & eAnimation) {
2237 mAnimTransactionPending = true;
2238 }
2239 while (mTransactionPending) {
2240 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2241 if (CC_UNLIKELY(err != NO_ERROR)) {
2242 // just in case something goes wrong in SF, return to the
2243 // called after a few seconds.
2244 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2245 mTransactionPending = false;
2246 break;
2247 }
2248 }
2249 }
2250}
2251
2252uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2253{
2254 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2255 if (dpyIdx < 0)
2256 return 0;
2257
2258 uint32_t flags = 0;
2259 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2260 if (disp.isValid()) {
2261 const uint32_t what = s.what;
2262 if (what & DisplayState::eSurfaceChanged) {
2263 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2264 disp.surface = s.surface;
2265 flags |= eDisplayTransactionNeeded;
2266 }
2267 }
2268 if (what & DisplayState::eLayerStackChanged) {
2269 if (disp.layerStack != s.layerStack) {
2270 disp.layerStack = s.layerStack;
2271 flags |= eDisplayTransactionNeeded;
2272 }
2273 }
2274 if (what & DisplayState::eDisplayProjectionChanged) {
2275 if (disp.orientation != s.orientation) {
2276 disp.orientation = s.orientation;
2277 flags |= eDisplayTransactionNeeded;
2278 }
2279 if (disp.frame != s.frame) {
2280 disp.frame = s.frame;
2281 flags |= eDisplayTransactionNeeded;
2282 }
2283 if (disp.viewport != s.viewport) {
2284 disp.viewport = s.viewport;
2285 flags |= eDisplayTransactionNeeded;
2286 }
2287 }
2288 if (what & DisplayState::eDisplaySizeChanged) {
2289 if (disp.width != s.width) {
2290 disp.width = s.width;
2291 flags |= eDisplayTransactionNeeded;
2292 }
2293 if (disp.height != s.height) {
2294 disp.height = s.height;
2295 flags |= eDisplayTransactionNeeded;
2296 }
2297 }
2298 }
2299 return flags;
2300}
2301
2302uint32_t SurfaceFlinger::setClientStateLocked(
2303 const sp<Client>& client,
2304 const layer_state_t& s)
2305{
2306 uint32_t flags = 0;
2307 sp<Layer> layer(client->getLayerUser(s.surface));
2308 if (layer != 0) {
2309 const uint32_t what = s.what;
Robert Carr99e27f02016-06-16 15:18:02 -07002310 bool geometryAppliesWithResize =
2311 what & layer_state_t::eGeometryAppliesWithResize;
Dan Stoza9e56aa02015-11-02 13:00:03 -08002312 if (what & layer_state_t::ePositionChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002313 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002314 flags |= eTraversalNeeded;
Robert Carr82364e32016-05-15 11:27:47 -07002315 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002316 }
2317 if (what & layer_state_t::eLayerChanged) {
2318 // NOTE: index needs to be calculated before we update the state
2319 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2320 if (layer->setLayer(s.z) && idx >= 0) {
2321 mCurrentState.layersSortedByZ.removeAt(idx);
2322 mCurrentState.layersSortedByZ.add(layer);
2323 // we need traversal (state changed)
2324 // AND transaction (list changed)
2325 flags |= eTransactionNeeded|eTraversalNeeded;
2326 }
2327 }
2328 if (what & layer_state_t::eSizeChanged) {
2329 if (layer->setSize(s.w, s.h)) {
2330 flags |= eTraversalNeeded;
2331 }
2332 }
2333 if (what & layer_state_t::eAlphaChanged) {
2334 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2335 flags |= eTraversalNeeded;
2336 }
2337 if (what & layer_state_t::eMatrixChanged) {
2338 if (layer->setMatrix(s.matrix))
2339 flags |= eTraversalNeeded;
2340 }
2341 if (what & layer_state_t::eTransparentRegionChanged) {
2342 if (layer->setTransparentRegionHint(s.transparentRegion))
2343 flags |= eTraversalNeeded;
2344 }
2345 if (what & layer_state_t::eFlagsChanged) {
2346 if (layer->setFlags(s.flags, s.mask))
2347 flags |= eTraversalNeeded;
2348 }
2349 if (what & layer_state_t::eCropChanged) {
Robert Carr99e27f02016-06-16 15:18:02 -07002350 if (layer->setCrop(s.crop, !geometryAppliesWithResize))
Dan Stoza9e56aa02015-11-02 13:00:03 -08002351 flags |= eTraversalNeeded;
2352 }
Pablo Ceballosacbe6782016-03-04 17:54:21 +00002353 if (what & layer_state_t::eFinalCropChanged) {
2354 if (layer->setFinalCrop(s.finalCrop))
2355 flags |= eTraversalNeeded;
2356 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002357 if (what & layer_state_t::eLayerStackChanged) {
2358 // NOTE: index needs to be calculated before we update the state
2359 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2360 if (layer->setLayerStack(s.layerStack) && idx >= 0) {
2361 mCurrentState.layersSortedByZ.removeAt(idx);
2362 mCurrentState.layersSortedByZ.add(layer);
2363 // we need traversal (state changed)
2364 // AND transaction (list changed)
2365 flags |= eTransactionNeeded|eTraversalNeeded;
2366 }
2367 }
2368 if (what & layer_state_t::eDeferTransaction) {
2369 layer->deferTransactionUntil(s.handle, s.frameNumber);
2370 // We don't trigger a traversal here because if no other state is
2371 // changed, we don't want this to cause any more work
2372 }
Robert Carrc3574f72016-03-24 12:19:32 -07002373 if (what & layer_state_t::eOverrideScalingModeChanged) {
2374 layer->setOverrideScalingMode(s.overrideScalingMode);
2375 // We don't trigger a traversal here because if no other state is
2376 // changed, we don't want this to cause any more work
2377 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002378 }
2379 return flags;
2380}
2381
2382status_t SurfaceFlinger::createLayer(
2383 const String8& name,
2384 const sp<Client>& client,
2385 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2386 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2387{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002388 if (int32_t(w|h) < 0) {
2389 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2390 int(w), int(h));
2391 return BAD_VALUE;
2392 }
2393
2394 status_t result = NO_ERROR;
2395
2396 sp<Layer> layer;
2397
2398 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2399 case ISurfaceComposerClient::eFXSurfaceNormal:
2400 result = createNormalLayer(client,
2401 name, w, h, flags, format,
2402 handle, gbp, &layer);
2403 break;
2404 case ISurfaceComposerClient::eFXSurfaceDim:
2405 result = createDimLayer(client,
2406 name, w, h, flags,
2407 handle, gbp, &layer);
2408 break;
2409 default:
2410 result = BAD_VALUE;
2411 break;
2412 }
2413
2414 if (result != NO_ERROR) {
2415 return result;
2416 }
2417
2418 result = addClientLayer(client, *handle, *gbp, layer);
2419 if (result != NO_ERROR) {
2420 return result;
2421 }
Irvel468051e2016-06-13 16:44:44 -07002422 mInterceptor.saveLayerCreate(layer);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002423
2424 setTransactionFlags(eTransactionNeeded);
2425 return result;
2426}
2427
2428status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2429 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2430 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2431{
2432 // initialize the surfaces
2433 switch (format) {
2434 case PIXEL_FORMAT_TRANSPARENT:
2435 case PIXEL_FORMAT_TRANSLUCENT:
2436 format = PIXEL_FORMAT_RGBA_8888;
2437 break;
2438 case PIXEL_FORMAT_OPAQUE:
2439 format = PIXEL_FORMAT_RGBX_8888;
2440 break;
2441 }
2442
2443 *outLayer = new Layer(this, client, name, w, h, flags);
2444 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2445 if (err == NO_ERROR) {
2446 *handle = (*outLayer)->getHandle();
2447 *gbp = (*outLayer)->getProducer();
2448 }
2449
2450 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2451 return err;
2452}
2453
2454status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2455 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2456 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2457{
2458 *outLayer = new LayerDim(this, client, name, w, h, flags);
2459 *handle = (*outLayer)->getHandle();
2460 *gbp = (*outLayer)->getProducer();
2461 return NO_ERROR;
2462}
2463
2464status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2465{
2466 // called by the window manager when it wants to remove a Layer
2467 status_t err = NO_ERROR;
2468 sp<Layer> l(client->getLayerUser(handle));
2469 if (l != NULL) {
Irvel468051e2016-06-13 16:44:44 -07002470 mInterceptor.saveLayerDelete(l);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002471 err = removeLayer(l);
2472 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2473 "error removing layer=%p (%s)", l.get(), strerror(-err));
2474 }
2475 return err;
2476}
2477
2478status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2479{
2480 // called by ~LayerCleaner() when all references to the IBinder (handle)
2481 // are gone
2482 status_t err = NO_ERROR;
2483 sp<Layer> l(layer.promote());
2484 if (l != NULL) {
2485 err = removeLayer(l);
2486 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2487 "error removing layer=%p (%s)", l.get(), strerror(-err));
2488 }
2489 return err;
2490}
2491
2492// ---------------------------------------------------------------------------
2493
2494void SurfaceFlinger::onInitializeDisplays() {
2495 // reset screen orientation and use primary layer stack
2496 Vector<ComposerState> state;
2497 Vector<DisplayState> displays;
2498 DisplayState d;
2499 d.what = DisplayState::eDisplayProjectionChanged |
2500 DisplayState::eLayerStackChanged;
2501 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2502 d.layerStack = 0;
2503 d.orientation = DisplayState::eOrientationDefault;
2504 d.frame.makeInvalid();
2505 d.viewport.makeInvalid();
2506 d.width = 0;
2507 d.height = 0;
2508 displays.add(d);
2509 setTransactionState(state, displays, 0);
2510 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2511
2512 const nsecs_t period =
2513 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2514 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2515}
2516
2517void SurfaceFlinger::initializeDisplays() {
2518 class MessageScreenInitialized : public MessageBase {
2519 SurfaceFlinger* flinger;
2520 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07002521 explicit MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002522 virtual bool handler() {
2523 flinger->onInitializeDisplays();
2524 return true;
2525 }
2526 };
2527 sp<MessageBase> msg = new MessageScreenInitialized(this);
2528 postMessageAsync(msg); // we may be called from main thread, use async message
2529}
2530
2531void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2532 int mode) {
2533 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2534 this);
2535 int32_t type = hw->getDisplayType();
2536 int currentMode = hw->getPowerMode();
2537
2538 if (mode == currentMode) {
2539 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2540 return;
2541 }
2542
2543 hw->setPowerMode(mode);
2544 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2545 ALOGW("Trying to set power mode for virtual display");
2546 return;
2547 }
2548
2549 if (currentMode == HWC_POWER_MODE_OFF) {
2550 getHwComposer().setPowerMode(type, mode);
2551 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2552 // FIXME: eventthread only knows about the main display right now
2553 mEventThread->onScreenAcquired();
2554 resyncToHardwareVsync(true);
2555 }
2556
2557 mVisibleRegionsDirty = true;
2558 mHasPoweredOff = true;
2559 repaintEverything();
2560 } else if (mode == HWC_POWER_MODE_OFF) {
2561 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2562 disableHardwareVsync(true); // also cancels any in-progress resync
2563
2564 // FIXME: eventthread only knows about the main display right now
2565 mEventThread->onScreenReleased();
2566 }
2567
2568 getHwComposer().setPowerMode(type, mode);
2569 mVisibleRegionsDirty = true;
2570 // from this point on, SF will stop drawing on this display
2571 } else {
2572 getHwComposer().setPowerMode(type, mode);
2573 }
2574}
2575
2576void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2577 class MessageSetPowerMode: public MessageBase {
2578 SurfaceFlinger& mFlinger;
2579 sp<IBinder> mDisplay;
2580 int mMode;
2581 public:
2582 MessageSetPowerMode(SurfaceFlinger& flinger,
2583 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2584 mDisplay(disp) { mMode = mode; }
2585 virtual bool handler() {
2586 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2587 if (hw == NULL) {
2588 ALOGE("Attempt to set power mode = %d for null display %p",
2589 mMode, mDisplay.get());
2590 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2591 ALOGW("Attempt to set power mode = %d for virtual display",
2592 mMode);
2593 } else {
2594 mFlinger.setPowerModeInternal(hw, mMode);
2595 }
2596 return true;
2597 }
2598 };
2599 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2600 postMessageSync(msg);
2601}
2602
2603// ---------------------------------------------------------------------------
2604
2605status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2606{
2607 String8 result;
2608
2609 IPCThreadState* ipc = IPCThreadState::self();
2610 const int pid = ipc->getCallingPid();
2611 const int uid = ipc->getCallingUid();
2612 if ((uid != AID_SHELL) &&
2613 !PermissionCache::checkPermission(sDump, pid, uid)) {
2614 result.appendFormat("Permission Denial: "
2615 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2616 } else {
2617 // Try to get the main lock, but give up after one second
2618 // (this would indicate SF is stuck, but we want to be able to
2619 // print something in dumpsys).
2620 status_t err = mStateLock.timedLock(s2ns(1));
2621 bool locked = (err == NO_ERROR);
2622 if (!locked) {
2623 result.appendFormat(
2624 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2625 "dumping anyways (no locks held)\n", strerror(-err), err);
2626 }
2627
2628 bool dumpAll = true;
2629 size_t index = 0;
2630 size_t numArgs = args.size();
2631 if (numArgs) {
2632 if ((index < numArgs) &&
2633 (args[index] == String16("--list"))) {
2634 index++;
2635 listLayersLocked(args, index, result);
2636 dumpAll = false;
2637 }
2638
2639 if ((index < numArgs) &&
2640 (args[index] == String16("--latency"))) {
2641 index++;
2642 dumpStatsLocked(args, index, result);
2643 dumpAll = false;
2644 }
2645
2646 if ((index < numArgs) &&
2647 (args[index] == String16("--latency-clear"))) {
2648 index++;
2649 clearStatsLocked(args, index, result);
2650 dumpAll = false;
2651 }
2652
2653 if ((index < numArgs) &&
2654 (args[index] == String16("--dispsync"))) {
2655 index++;
2656 mPrimaryDispSync.dump(result);
2657 dumpAll = false;
2658 }
2659
2660 if ((index < numArgs) &&
2661 (args[index] == String16("--static-screen"))) {
2662 index++;
2663 dumpStaticScreenStats(result);
2664 dumpAll = false;
2665 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002666
2667 if ((index < numArgs) &&
2668 (args[index] == String16("--fences"))) {
2669 index++;
2670 mFenceTracker.dump(&result);
2671 dumpAll = false;
2672 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002673 }
2674
2675 if (dumpAll) {
2676 dumpAllLocked(args, index, result);
2677 }
2678
2679 if (locked) {
2680 mStateLock.unlock();
2681 }
2682 }
2683 write(fd, result.string(), result.size());
2684 return NO_ERROR;
2685}
2686
2687void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2688 size_t& /* index */, String8& result) const
2689{
2690 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2691 const size_t count = currentLayers.size();
2692 for (size_t i=0 ; i<count ; i++) {
2693 const sp<Layer>& layer(currentLayers[i]);
2694 result.appendFormat("%s\n", layer->getName().string());
2695 }
2696}
2697
2698void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2699 String8& result) const
2700{
2701 String8 name;
2702 if (index < args.size()) {
2703 name = String8(args[index]);
2704 index++;
2705 }
2706
2707 const nsecs_t period =
2708 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2709 result.appendFormat("%" PRId64 "\n", period);
2710
2711 if (name.isEmpty()) {
2712 mAnimFrameTracker.dumpStats(result);
2713 } else {
2714 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2715 const size_t count = currentLayers.size();
2716 for (size_t i=0 ; i<count ; i++) {
2717 const sp<Layer>& layer(currentLayers[i]);
2718 if (name == layer->getName()) {
2719 layer->dumpFrameStats(result);
2720 }
2721 }
2722 }
2723}
2724
2725void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2726 String8& /* result */)
2727{
2728 String8 name;
2729 if (index < args.size()) {
2730 name = String8(args[index]);
2731 index++;
2732 }
2733
2734 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2735 const size_t count = currentLayers.size();
2736 for (size_t i=0 ; i<count ; i++) {
2737 const sp<Layer>& layer(currentLayers[i]);
2738 if (name.isEmpty() || (name == layer->getName())) {
2739 layer->clearFrameStats();
2740 }
2741 }
2742
2743 mAnimFrameTracker.clearStats();
2744}
2745
2746// This should only be called from the main thread. Otherwise it would need
2747// the lock and should use mCurrentState rather than mDrawingState.
2748void SurfaceFlinger::logFrameStats() {
2749 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2750 const size_t count = drawingLayers.size();
2751 for (size_t i=0 ; i<count ; i++) {
2752 const sp<Layer>& layer(drawingLayers[i]);
2753 layer->logFrameStats();
2754 }
2755
2756 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2757}
2758
2759/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2760{
2761 static const char* config =
2762 " [sf"
2763#ifdef HAS_CONTEXT_PRIORITY
2764 " HAS_CONTEXT_PRIORITY"
2765#endif
2766#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2767 " NEVER_DEFAULT_TO_ASYNC_MODE"
2768#endif
2769#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2770 " TARGET_DISABLE_TRIPLE_BUFFERING"
2771#endif
2772 "]";
2773 result.append(config);
2774}
2775
2776void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2777{
2778 result.appendFormat("Static screen stats:\n");
2779 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2780 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2781 float percent = 100.0f *
2782 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2783 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2784 b + 1, bucketTimeSec, percent);
2785 }
2786 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2787 float percent = 100.0f *
2788 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2789 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2790 NUM_BUCKETS - 1, bucketTimeSec, percent);
2791}
2792
Dan Stozae77c7662016-05-13 11:37:28 -07002793void SurfaceFlinger::recordBufferingStats(const char* layerName,
2794 std::vector<OccupancyTracker::Segment>&& history) {
2795 Mutex::Autolock lock(mBufferingStatsMutex);
2796 auto& stats = mBufferingStats[layerName];
2797 for (const auto& segment : history) {
2798 if (!segment.usedThirdBuffer) {
2799 stats.twoBufferTime += segment.totalTime;
2800 }
2801 if (segment.occupancyAverage < 1.0f) {
2802 stats.doubleBufferedTime += segment.totalTime;
2803 } else if (segment.occupancyAverage < 2.0f) {
2804 stats.tripleBufferedTime += segment.totalTime;
2805 }
2806 ++stats.numSegments;
2807 stats.totalTime += segment.totalTime;
2808 }
2809}
2810
2811void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2812 result.append("Buffering stats:\n");
2813 result.append(" [Layer name] <Active time> <Two buffer> "
2814 "<Double buffered> <Triple buffered>\n");
2815 Mutex::Autolock lock(mBufferingStatsMutex);
2816 typedef std::tuple<std::string, float, float, float> BufferTuple;
2817 std::map<float, BufferTuple, std::greater<float>> sorted;
2818 for (const auto& statsPair : mBufferingStats) {
2819 const char* name = statsPair.first.c_str();
2820 const BufferingStats& stats = statsPair.second;
2821 if (stats.numSegments == 0) {
2822 continue;
2823 }
2824 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2825 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2826 stats.totalTime;
2827 float doubleBufferRatio = static_cast<float>(
2828 stats.doubleBufferedTime) / stats.totalTime;
2829 float tripleBufferRatio = static_cast<float>(
2830 stats.tripleBufferedTime) / stats.totalTime;
2831 sorted.insert({activeTime, {name, twoBufferRatio,
2832 doubleBufferRatio, tripleBufferRatio}});
2833 }
2834 for (const auto& sortedPair : sorted) {
2835 float activeTime = sortedPair.first;
2836 const BufferTuple& values = sortedPair.second;
2837 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2838 std::get<0>(values).c_str(), activeTime,
2839 std::get<1>(values), std::get<2>(values),
2840 std::get<3>(values));
2841 }
2842 result.append("\n");
2843}
2844
Dan Stoza9e56aa02015-11-02 13:00:03 -08002845void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2846 String8& result) const
2847{
2848 bool colorize = false;
2849 if (index < args.size()
2850 && (args[index] == String16("--color"))) {
2851 colorize = true;
2852 index++;
2853 }
2854
2855 Colorizer colorizer(colorize);
2856
2857 // figure out if we're stuck somewhere
2858 const nsecs_t now = systemTime();
2859 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2860 const nsecs_t inTransaction(mDebugInTransaction);
2861 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2862 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2863
2864 /*
2865 * Dump library configuration.
2866 */
2867
2868 colorizer.bold(result);
2869 result.append("Build configuration:");
2870 colorizer.reset(result);
2871 appendSfConfigString(result);
2872 appendUiConfigString(result);
2873 appendGuiConfigString(result);
2874 result.append("\n");
2875
2876 colorizer.bold(result);
2877 result.append("Sync configuration: ");
2878 colorizer.reset(result);
2879 result.append(SyncFeatures::getInstance().toString());
2880 result.append("\n");
2881
2882 colorizer.bold(result);
2883 result.append("DispSync configuration: ");
2884 colorizer.reset(result);
2885 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2886 "present offset %d ns (refresh %" PRId64 " ns)",
2887 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2888 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2889 result.append("\n");
2890
2891 // Dump static screen stats
2892 result.append("\n");
2893 dumpStaticScreenStats(result);
2894 result.append("\n");
2895
Dan Stozae77c7662016-05-13 11:37:28 -07002896 dumpBufferingStats(result);
2897
Dan Stoza9e56aa02015-11-02 13:00:03 -08002898 /*
2899 * Dump the visible layer list
2900 */
2901 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2902 const size_t count = currentLayers.size();
2903 colorizer.bold(result);
2904 result.appendFormat("Visible layers (count = %zu)\n", count);
2905 colorizer.reset(result);
2906 for (size_t i=0 ; i<count ; i++) {
2907 const sp<Layer>& layer(currentLayers[i]);
2908 layer->dump(result, colorizer);
2909 }
2910
2911 /*
2912 * Dump Display state
2913 */
2914
2915 colorizer.bold(result);
2916 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2917 colorizer.reset(result);
2918 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2919 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2920 hw->dump(result);
2921 }
2922
2923 /*
2924 * Dump SurfaceFlinger global state
2925 */
2926
2927 colorizer.bold(result);
2928 result.append("SurfaceFlinger global state:\n");
2929 colorizer.reset(result);
2930
2931 HWComposer& hwc(getHwComposer());
2932 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2933
2934 colorizer.bold(result);
2935 result.appendFormat("EGL implementation : %s\n",
2936 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2937 colorizer.reset(result);
2938 result.appendFormat("%s\n",
2939 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2940
2941 mRenderEngine->dump(result);
2942
2943 hw->undefinedRegion.dump(result, "undefinedRegion");
2944 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2945 hw->getOrientation(), hw->isDisplayOn());
2946 result.appendFormat(
2947 " last eglSwapBuffers() time: %f us\n"
2948 " last transaction time : %f us\n"
2949 " transaction-flags : %08x\n"
2950 " refresh-rate : %f fps\n"
2951 " x-dpi : %f\n"
2952 " y-dpi : %f\n"
2953 " gpu_to_cpu_unsupported : %d\n"
2954 ,
2955 mLastSwapBufferTime/1000.0,
2956 mLastTransactionTime/1000.0,
2957 mTransactionFlags,
2958 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2959 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2960 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2961 !mGpuToCpuSupported);
2962
2963 result.appendFormat(" eglSwapBuffers time: %f us\n",
2964 inSwapBuffersDuration/1000.0);
2965
2966 result.appendFormat(" transaction time: %f us\n",
2967 inTransactionDuration/1000.0);
2968
2969 /*
2970 * VSYNC state
2971 */
2972 mEventThread->dump(result);
2973
2974 /*
2975 * Dump HWComposer state
2976 */
2977 colorizer.bold(result);
2978 result.append("h/w composer state:\n");
2979 colorizer.reset(result);
2980 result.appendFormat(" h/w composer %s and %s\n",
2981 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2982 (mDebugDisableHWC || mDebugRegion || mDaltonize
2983 || mHasColorMatrix) ? "disabled" : "enabled");
2984 hwc.dump(result);
2985
2986 /*
2987 * Dump gralloc state
2988 */
2989 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2990 alloc.dump(result);
2991}
2992
2993const Vector< sp<Layer> >&
2994SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2995 // Note: mStateLock is held here
2996 wp<IBinder> dpy;
2997 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2998 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2999 dpy = mDisplays.keyAt(i);
3000 break;
3001 }
3002 }
3003 if (dpy == NULL) {
3004 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3005 // Just use the primary display so we have something to return
3006 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3007 }
3008 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3009}
3010
3011bool SurfaceFlinger::startDdmConnection()
3012{
3013 void* libddmconnection_dso =
3014 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3015 if (!libddmconnection_dso) {
3016 return false;
3017 }
3018 void (*DdmConnection_start)(const char* name);
3019 DdmConnection_start =
3020 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3021 if (!DdmConnection_start) {
3022 dlclose(libddmconnection_dso);
3023 return false;
3024 }
3025 (*DdmConnection_start)(getServiceName());
3026 return true;
3027}
3028
3029status_t SurfaceFlinger::onTransact(
3030 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3031{
3032 switch (code) {
3033 case CREATE_CONNECTION:
3034 case CREATE_DISPLAY:
3035 case SET_TRANSACTION_STATE:
3036 case BOOT_FINISHED:
3037 case CLEAR_ANIMATION_FRAME_STATS:
3038 case GET_ANIMATION_FRAME_STATS:
3039 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003040 case GET_HDR_CAPABILITIES:
Dan Stoza9e56aa02015-11-02 13:00:03 -08003041 {
3042 // codes that require permission check
3043 IPCThreadState* ipc = IPCThreadState::self();
3044 const int pid = ipc->getCallingPid();
3045 const int uid = ipc->getCallingUid();
3046 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3047 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3048 ALOGE("Permission Denial: "
3049 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3050 return PERMISSION_DENIED;
3051 }
3052 break;
3053 }
3054 case CAPTURE_SCREEN:
3055 {
3056 // codes that require permission check
3057 IPCThreadState* ipc = IPCThreadState::self();
3058 const int pid = ipc->getCallingPid();
3059 const int uid = ipc->getCallingUid();
3060 if ((uid != AID_GRAPHICS) &&
3061 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3062 ALOGE("Permission Denial: "
3063 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3064 return PERMISSION_DENIED;
3065 }
3066 break;
3067 }
3068 }
3069
3070 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3071 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3072 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3073 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3074 IPCThreadState* ipc = IPCThreadState::self();
3075 const int pid = ipc->getCallingPid();
3076 const int uid = ipc->getCallingUid();
3077 ALOGE("Permission Denial: "
3078 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3079 return PERMISSION_DENIED;
3080 }
3081 int n;
3082 switch (code) {
3083 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3084 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3085 return NO_ERROR;
3086 case 1002: // SHOW_UPDATES
3087 n = data.readInt32();
3088 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3089 invalidateHwcGeometry();
3090 repaintEverything();
3091 return NO_ERROR;
3092 case 1004:{ // repaint everything
3093 repaintEverything();
3094 return NO_ERROR;
3095 }
3096 case 1005:{ // force transaction
3097 setTransactionFlags(
3098 eTransactionNeeded|
3099 eDisplayTransactionNeeded|
3100 eTraversalNeeded);
3101 return NO_ERROR;
3102 }
3103 case 1006:{ // send empty update
3104 signalRefresh();
3105 return NO_ERROR;
3106 }
3107 case 1008: // toggle use of hw composer
3108 n = data.readInt32();
3109 mDebugDisableHWC = n ? 1 : 0;
3110 invalidateHwcGeometry();
3111 repaintEverything();
3112 return NO_ERROR;
3113 case 1009: // toggle use of transform hint
3114 n = data.readInt32();
3115 mDebugDisableTransformHint = n ? 1 : 0;
3116 invalidateHwcGeometry();
3117 repaintEverything();
3118 return NO_ERROR;
3119 case 1010: // interrogate.
3120 reply->writeInt32(0);
3121 reply->writeInt32(0);
3122 reply->writeInt32(mDebugRegion);
3123 reply->writeInt32(0);
3124 reply->writeInt32(mDebugDisableHWC);
3125 return NO_ERROR;
3126 case 1013: {
3127 Mutex::Autolock _l(mStateLock);
3128 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3129 reply->writeInt32(hw->getPageFlipCount());
3130 return NO_ERROR;
3131 }
3132 case 1014: {
3133 // daltonize
3134 n = data.readInt32();
3135 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003136 case 1:
3137 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3138 break;
3139 case 2:
3140 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3141 break;
3142 case 3:
3143 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3144 break;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003145 }
3146 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003147 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003149 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003150 }
3151 mDaltonize = n > 0;
3152 invalidateHwcGeometry();
3153 repaintEverything();
3154 return NO_ERROR;
3155 }
3156 case 1015: {
3157 // apply a color matrix
3158 n = data.readInt32();
3159 mHasColorMatrix = n ? 1 : 0;
3160 if (n) {
3161 // color matrix is sent as mat3 matrix followed by vec3
3162 // offset, then packed into a mat4 where the last row is
3163 // the offset and extra values are 0
3164 for (size_t i = 0 ; i < 4; i++) {
3165 for (size_t j = 0; j < 4; j++) {
3166 mColorMatrix[i][j] = data.readFloat();
3167 }
3168 }
3169 } else {
3170 mColorMatrix = mat4();
3171 }
3172 invalidateHwcGeometry();
3173 repaintEverything();
3174 return NO_ERROR;
3175 }
3176 // This is an experimental interface
3177 // Needs to be shifted to proper binder interface when we productize
3178 case 1016: {
3179 n = data.readInt32();
3180 mPrimaryDispSync.setRefreshSkipCount(n);
3181 return NO_ERROR;
3182 }
3183 case 1017: {
3184 n = data.readInt32();
3185 mForceFullDamage = static_cast<bool>(n);
3186 return NO_ERROR;
3187 }
3188 case 1018: { // Modify Choreographer's phase offset
3189 n = data.readInt32();
3190 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3191 return NO_ERROR;
3192 }
3193 case 1019: { // Modify SurfaceFlinger's phase offset
3194 n = data.readInt32();
3195 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3196 return NO_ERROR;
3197 }
Irvel468051e2016-06-13 16:44:44 -07003198 case 1020: { // Layer updates interceptor
3199 n = data.readInt32();
3200 if (n) {
3201 ALOGV("Interceptor enabled");
3202 mInterceptor.enable(mDrawingState.layersSortedByZ);
3203 }
3204 else{
3205 ALOGV("Interceptor disabled");
3206 mInterceptor.disable();
3207 }
3208 return NO_ERROR;
3209 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003210 }
3211 }
3212 return err;
3213}
3214
3215void SurfaceFlinger::repaintEverything() {
3216 android_atomic_or(1, &mRepaintEverything);
3217 signalTransaction();
3218}
3219
3220// ---------------------------------------------------------------------------
3221// Capture screen into an IGraphiBufferProducer
3222// ---------------------------------------------------------------------------
3223
3224/* The code below is here to handle b/8734824
3225 *
3226 * We create a IGraphicBufferProducer wrapper that forwards all calls
3227 * from the surfaceflinger thread to the calling binder thread, where they
3228 * are executed. This allows the calling thread in the calling process to be
3229 * reused and not depend on having "enough" binder threads to handle the
3230 * requests.
3231 */
3232class GraphicProducerWrapper : public BBinder, public MessageHandler {
3233 /* Parts of GraphicProducerWrapper are run on two different threads,
3234 * communicating by sending messages via Looper but also by shared member
3235 * data. Coherence maintenance is subtle and in places implicit (ugh).
3236 *
3237 * Don't rely on Looper's sendMessage/handleMessage providing
3238 * release/acquire semantics for any data not actually in the Message.
3239 * Data going from surfaceflinger to binder threads needs to be
3240 * synchronized explicitly.
3241 *
3242 * Barrier open/wait do provide release/acquire semantics. This provides
3243 * implicit synchronization for data coming back from binder to
3244 * surfaceflinger threads.
3245 */
3246
3247 sp<IGraphicBufferProducer> impl;
3248 sp<Looper> looper;
3249 status_t result;
3250 bool exitPending;
3251 bool exitRequested;
3252 Barrier barrier;
3253 uint32_t code;
3254 Parcel const* data;
3255 Parcel* reply;
3256
3257 enum {
3258 MSG_API_CALL,
3259 MSG_EXIT
3260 };
3261
3262 /*
3263 * Called on surfaceflinger thread. This is called by our "fake"
3264 * BpGraphicBufferProducer. We package the data and reply Parcel and
3265 * forward them to the binder thread.
3266 */
3267 virtual status_t transact(uint32_t code,
3268 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3269 this->code = code;
3270 this->data = &data;
3271 this->reply = reply;
3272 if (exitPending) {
3273 // if we've exited, we run the message synchronously right here.
3274 // note (JH): as far as I can tell from looking at the code, this
3275 // never actually happens. if it does, i'm not sure if it happens
3276 // on the surfaceflinger or binder thread.
3277 handleMessage(Message(MSG_API_CALL));
3278 } else {
3279 barrier.close();
3280 // Prevent stores to this->{code, data, reply} from being
3281 // reordered later than the construction of Message.
3282 atomic_thread_fence(memory_order_release);
3283 looper->sendMessage(this, Message(MSG_API_CALL));
3284 barrier.wait();
3285 }
3286 return result;
3287 }
3288
3289 /*
3290 * here we run on the binder thread. All we've got to do is
3291 * call the real BpGraphicBufferProducer.
3292 */
3293 virtual void handleMessage(const Message& message) {
3294 int what = message.what;
3295 // Prevent reads below from happening before the read from Message
3296 atomic_thread_fence(memory_order_acquire);
3297 if (what == MSG_API_CALL) {
3298 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3299 barrier.open();
3300 } else if (what == MSG_EXIT) {
3301 exitRequested = true;
3302 }
3303 }
3304
3305public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003306 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003307 : impl(impl),
3308 looper(new Looper(true)),
3309 result(NO_ERROR),
3310 exitPending(false),
3311 exitRequested(false),
3312 code(0),
3313 data(NULL),
3314 reply(NULL)
3315 {}
3316
3317 // Binder thread
3318 status_t waitForResponse() {
3319 do {
3320 looper->pollOnce(-1);
3321 } while (!exitRequested);
3322 return result;
3323 }
3324
3325 // Client thread
3326 void exit(status_t result) {
3327 this->result = result;
3328 exitPending = true;
3329 // Ensure this->result is visible to the binder thread before it
3330 // handles the message.
3331 atomic_thread_fence(memory_order_release);
3332 looper->sendMessage(this, Message(MSG_EXIT));
3333 }
3334};
3335
3336
3337status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3338 const sp<IGraphicBufferProducer>& producer,
3339 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3340 uint32_t minLayerZ, uint32_t maxLayerZ,
3341 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3342
3343 if (CC_UNLIKELY(display == 0))
3344 return BAD_VALUE;
3345
3346 if (CC_UNLIKELY(producer == 0))
3347 return BAD_VALUE;
3348
3349 // if we have secure windows on this display, never allow the screen capture
3350 // unless the producer interface is local (i.e.: we can take a screenshot for
3351 // ourselves).
3352 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3353
3354 // Convert to surfaceflinger's internal rotation type.
3355 Transform::orientation_flags rotationFlags;
3356 switch (rotation) {
3357 case ISurfaceComposer::eRotateNone:
3358 rotationFlags = Transform::ROT_0;
3359 break;
3360 case ISurfaceComposer::eRotate90:
3361 rotationFlags = Transform::ROT_90;
3362 break;
3363 case ISurfaceComposer::eRotate180:
3364 rotationFlags = Transform::ROT_180;
3365 break;
3366 case ISurfaceComposer::eRotate270:
3367 rotationFlags = Transform::ROT_270;
3368 break;
3369 default:
3370 rotationFlags = Transform::ROT_0;
3371 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3372 break;
3373 }
3374
3375 class MessageCaptureScreen : public MessageBase {
3376 SurfaceFlinger* flinger;
3377 sp<IBinder> display;
3378 sp<IGraphicBufferProducer> producer;
3379 Rect sourceCrop;
3380 uint32_t reqWidth, reqHeight;
3381 uint32_t minLayerZ,maxLayerZ;
3382 bool useIdentityTransform;
3383 Transform::orientation_flags rotation;
3384 status_t result;
3385 bool isLocalScreenshot;
3386 public:
3387 MessageCaptureScreen(SurfaceFlinger* flinger,
3388 const sp<IBinder>& display,
3389 const sp<IGraphicBufferProducer>& producer,
3390 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3391 uint32_t minLayerZ, uint32_t maxLayerZ,
3392 bool useIdentityTransform,
3393 Transform::orientation_flags rotation,
3394 bool isLocalScreenshot)
3395 : flinger(flinger), display(display), producer(producer),
3396 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3397 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3398 useIdentityTransform(useIdentityTransform),
3399 rotation(rotation), result(PERMISSION_DENIED),
3400 isLocalScreenshot(isLocalScreenshot)
3401 {
3402 }
3403 status_t getResult() const {
3404 return result;
3405 }
3406 virtual bool handler() {
3407 Mutex::Autolock _l(flinger->mStateLock);
3408 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3409 result = flinger->captureScreenImplLocked(hw, producer,
3410 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3411 useIdentityTransform, rotation, isLocalScreenshot);
3412 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3413 return true;
3414 }
3415 };
3416
Dan Stoza9e56aa02015-11-02 13:00:03 -08003417 // this creates a "fake" BBinder which will serve as a "fake" remote
3418 // binder to receive the marshaled calls and forward them to the
3419 // real remote (a BpGraphicBufferProducer)
3420 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3421
3422 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3423 // which does the marshaling work forwards to our "fake remote" above.
3424 sp<MessageBase> msg = new MessageCaptureScreen(this,
3425 display, IGraphicBufferProducer::asInterface( wrapper ),
3426 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3427 useIdentityTransform, rotationFlags, isLocalScreenshot);
3428
3429 status_t res = postMessageAsync(msg);
3430 if (res == NO_ERROR) {
3431 res = wrapper->waitForResponse();
3432 }
3433 return res;
3434}
3435
3436
3437void SurfaceFlinger::renderScreenImplLocked(
3438 const sp<const DisplayDevice>& hw,
3439 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3440 uint32_t minLayerZ, uint32_t maxLayerZ,
3441 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3442{
3443 ATRACE_CALL();
3444 RenderEngine& engine(getRenderEngine());
3445
3446 // get screen geometry
3447 const int32_t hw_w = hw->getWidth();
3448 const int32_t hw_h = hw->getHeight();
3449 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3450 static_cast<int32_t>(reqHeight) != hw_h;
3451
3452 // if a default or invalid sourceCrop is passed in, set reasonable values
3453 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3454 !sourceCrop.isValid()) {
3455 sourceCrop.setLeftTop(Point(0, 0));
3456 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3457 }
3458
3459 // ensure that sourceCrop is inside screen
3460 if (sourceCrop.left < 0) {
3461 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3462 }
3463 if (sourceCrop.right > hw_w) {
3464 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3465 }
3466 if (sourceCrop.top < 0) {
3467 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3468 }
3469 if (sourceCrop.bottom > hw_h) {
3470 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3471 }
3472
3473 // make sure to clear all GL error flags
3474 engine.checkErrors();
3475
3476 // set-up our viewport
3477 engine.setViewportAndProjection(
3478 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3479 engine.disableTexturing();
3480
3481 // redraw the screen entirely...
3482 engine.clearWithColor(0, 0, 0, 1);
3483
3484 const LayerVector& layers( mDrawingState.layersSortedByZ );
3485 const size_t count = layers.size();
3486 for (size_t i=0 ; i<count ; ++i) {
3487 const sp<Layer>& layer(layers[i]);
3488 const Layer::State& state(layer->getDrawingState());
3489 if (state.layerStack == hw->getLayerStack()) {
3490 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3491 if (layer->isVisible()) {
3492 if (filtering) layer->setFiltering(true);
3493 layer->draw(hw, useIdentityTransform);
3494 if (filtering) layer->setFiltering(false);
3495 }
3496 }
3497 }
3498 }
3499
3500 // compositionComplete is needed for older driver
3501 hw->compositionComplete();
3502 hw->setViewportAndProjection();
3503}
3504
3505
3506status_t SurfaceFlinger::captureScreenImplLocked(
3507 const sp<const DisplayDevice>& hw,
3508 const sp<IGraphicBufferProducer>& producer,
3509 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3510 uint32_t minLayerZ, uint32_t maxLayerZ,
3511 bool useIdentityTransform, Transform::orientation_flags rotation,
3512 bool isLocalScreenshot)
3513{
3514 ATRACE_CALL();
3515
3516 // get screen geometry
3517 uint32_t hw_w = hw->getWidth();
3518 uint32_t hw_h = hw->getHeight();
3519
3520 if (rotation & Transform::ROT_90) {
3521 std::swap(hw_w, hw_h);
3522 }
3523
3524 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3525 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3526 reqWidth, reqHeight, hw_w, hw_h);
3527 return BAD_VALUE;
3528 }
3529
3530 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3531 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3532
3533 bool secureLayerIsVisible = false;
3534 const LayerVector& layers(mDrawingState.layersSortedByZ);
3535 const size_t count = layers.size();
3536 for (size_t i = 0 ; i < count ; ++i) {
3537 const sp<Layer>& layer(layers[i]);
3538 const Layer::State& state(layer->getDrawingState());
3539 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3540 state.z <= maxLayerZ && layer->isVisible() &&
3541 layer->isSecure()) {
3542 secureLayerIsVisible = true;
3543 }
3544 }
3545
3546 if (!isLocalScreenshot && secureLayerIsVisible) {
3547 ALOGW("FB is protected: PERMISSION_DENIED");
3548 return PERMISSION_DENIED;
3549 }
3550
3551 // create a surface (because we're a producer, and we need to
3552 // dequeue/queue a buffer)
3553 sp<Surface> sur = new Surface(producer, false);
3554 ANativeWindow* window = sur.get();
3555
3556 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3557 if (result == NO_ERROR) {
3558 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3559 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3560
3561 int err = 0;
3562 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3563 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3564 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3565 err |= native_window_set_usage(window, usage);
3566
3567 if (err == NO_ERROR) {
3568 ANativeWindowBuffer* buffer;
3569 /* TODO: Once we have the sync framework everywhere this can use
3570 * server-side waits on the fence that dequeueBuffer returns.
3571 */
3572 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3573 if (result == NO_ERROR) {
3574 int syncFd = -1;
3575 // create an EGLImage from the buffer so we can later
3576 // turn it into a texture
3577 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3578 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3579 if (image != EGL_NO_IMAGE_KHR) {
3580 // this binds the given EGLImage as a framebuffer for the
3581 // duration of this scope.
3582 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3583 if (imageBond.getStatus() == NO_ERROR) {
3584 // this will in fact render into our dequeued buffer
3585 // via an FBO, which means we didn't have to create
3586 // an EGLSurface and therefore we're not
3587 // dependent on the context's EGLConfig.
3588 renderScreenImplLocked(
3589 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3590 useIdentityTransform, rotation);
3591
3592 // Attempt to create a sync khr object that can produce a sync point. If that
3593 // isn't available, create a non-dupable sync object in the fallback path and
3594 // wait on it directly.
3595 EGLSyncKHR sync;
3596 if (!DEBUG_SCREENSHOTS) {
3597 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3598 // native fence fd will not be populated until flush() is done.
3599 getRenderEngine().flush();
3600 } else {
3601 sync = EGL_NO_SYNC_KHR;
3602 }
3603 if (sync != EGL_NO_SYNC_KHR) {
3604 // get the sync fd
3605 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3606 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3607 ALOGW("captureScreen: failed to dup sync khr object");
3608 syncFd = -1;
3609 }
3610 eglDestroySyncKHR(mEGLDisplay, sync);
3611 } else {
3612 // fallback path
3613 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3614 if (sync != EGL_NO_SYNC_KHR) {
3615 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3616 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3617 EGLint eglErr = eglGetError();
3618 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3619 ALOGW("captureScreen: fence wait timed out");
3620 } else {
3621 ALOGW_IF(eglErr != EGL_SUCCESS,
3622 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3623 }
3624 eglDestroySyncKHR(mEGLDisplay, sync);
3625 } else {
3626 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3627 }
3628 }
3629 if (DEBUG_SCREENSHOTS) {
3630 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3631 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3632 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3633 hw, minLayerZ, maxLayerZ);
3634 delete [] pixels;
3635 }
3636
3637 } else {
3638 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3639 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003640 window->cancelBuffer(window, buffer, syncFd);
3641 buffer = NULL;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003642 }
3643 // destroy our image
3644 eglDestroyImageKHR(mEGLDisplay, image);
3645 } else {
3646 result = BAD_VALUE;
3647 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003648 if (buffer) {
3649 // queueBuffer takes ownership of syncFd
3650 result = window->queueBuffer(window, buffer, syncFd);
3651 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003652 }
3653 } else {
3654 result = BAD_VALUE;
3655 }
3656 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3657 }
3658
3659 return result;
3660}
3661
Pablo Ceballosce796e72016-02-04 19:10:51 -08003662bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3663 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3664 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3665}
3666
Dan Stoza9e56aa02015-11-02 13:00:03 -08003667void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3668 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3669 if (DEBUG_SCREENSHOTS) {
3670 for (size_t y=0 ; y<h ; y++) {
3671 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3672 for (size_t x=0 ; x<w ; x++) {
3673 if (p[x] != 0xFF000000) return;
3674 }
3675 }
3676 ALOGE("*** we just took a black screenshot ***\n"
3677 "requested minz=%d, maxz=%d, layerStack=%d",
3678 minLayerZ, maxLayerZ, hw->getLayerStack());
3679 const LayerVector& layers( mDrawingState.layersSortedByZ );
3680 const size_t count = layers.size();
3681 for (size_t i=0 ; i<count ; ++i) {
3682 const sp<Layer>& layer(layers[i]);
3683 const Layer::State& state(layer->getDrawingState());
3684 const bool visible = (state.layerStack == hw->getLayerStack())
3685 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3686 && (layer->isVisible());
3687 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3688 visible ? '+' : '-',
3689 i, layer->getName().string(), state.layerStack, state.z,
3690 layer->isVisible(), state.flags, state.alpha);
3691 }
3692 }
3693}
3694
3695// ---------------------------------------------------------------------------
3696
3697SurfaceFlinger::LayerVector::LayerVector() {
3698}
3699
3700SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3701 : SortedVector<sp<Layer> >(rhs) {
3702}
3703
3704int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3705 const void* rhs) const
3706{
3707 // sort layers per layer-stack, then by z-order and finally by sequence
3708 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3709 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3710
3711 uint32_t ls = l->getCurrentState().layerStack;
3712 uint32_t rs = r->getCurrentState().layerStack;
3713 if (ls != rs)
3714 return ls - rs;
3715
3716 uint32_t lz = l->getCurrentState().z;
3717 uint32_t rz = r->getCurrentState().z;
3718 if (lz != rz)
3719 return lz - rz;
3720
3721 return l->sequence - r->sequence;
3722}
3723
3724// ---------------------------------------------------------------------------
3725
3726SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3727 : type(DisplayDevice::DISPLAY_ID_INVALID),
3728 layerStack(DisplayDevice::NO_LAYER_STACK),
3729 orientation(0),
3730 width(0),
3731 height(0),
3732 isSecure(false) {
3733}
3734
3735SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3736 DisplayDevice::DisplayType type, bool isSecure)
3737 : type(type),
3738 layerStack(DisplayDevice::NO_LAYER_STACK),
3739 orientation(0),
3740 width(0),
3741 height(0),
3742 isSecure(isSecure) {
3743 viewport.makeInvalid();
3744 frame.makeInvalid();
3745}
3746
3747// ---------------------------------------------------------------------------
3748
3749}; // namespace android
3750
3751
3752#if defined(__gl_h_)
3753#error "don't include gl/gl.h in this file"
3754#endif
3755
3756#if defined(__gl2_h_)
3757#error "don't include gl2/gl2.h in this file"
3758#endif