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