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