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