blob: 2cf18283dca72d516a723eac6da2575e7e026bd0 [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
2196status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2197 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
2541 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;
2549}
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) {
2609 getHwComposer().setPowerMode(type, mode);
2610 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2611 // FIXME: eventthread only knows about the main display right now
2612 mEventThread->onScreenAcquired();
2613 resyncToHardwareVsync(true);
2614 }
2615
2616 mVisibleRegionsDirty = true;
2617 mHasPoweredOff = true;
2618 repaintEverything();
2619 } else if (mode == HWC_POWER_MODE_OFF) {
2620 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2621 disableHardwareVsync(true); // also cancels any in-progress resync
2622
2623 // FIXME: eventthread only knows about the main display right now
2624 mEventThread->onScreenReleased();
2625 }
2626
2627 getHwComposer().setPowerMode(type, mode);
2628 mVisibleRegionsDirty = true;
2629 // from this point on, SF will stop drawing on this display
2630 } else {
2631 getHwComposer().setPowerMode(type, mode);
2632 }
2633}
2634
2635void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2636 class MessageSetPowerMode: public MessageBase {
2637 SurfaceFlinger& mFlinger;
2638 sp<IBinder> mDisplay;
2639 int mMode;
2640 public:
2641 MessageSetPowerMode(SurfaceFlinger& flinger,
2642 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2643 mDisplay(disp) { mMode = mode; }
2644 virtual bool handler() {
2645 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2646 if (hw == NULL) {
2647 ALOGE("Attempt to set power mode = %d for null display %p",
2648 mMode, mDisplay.get());
2649 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2650 ALOGW("Attempt to set power mode = %d for virtual display",
2651 mMode);
2652 } else {
2653 mFlinger.setPowerModeInternal(hw, mMode);
2654 }
2655 return true;
2656 }
2657 };
2658 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2659 postMessageSync(msg);
2660}
2661
2662// ---------------------------------------------------------------------------
2663
2664status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2665{
2666 String8 result;
2667
2668 IPCThreadState* ipc = IPCThreadState::self();
2669 const int pid = ipc->getCallingPid();
2670 const int uid = ipc->getCallingUid();
2671 if ((uid != AID_SHELL) &&
2672 !PermissionCache::checkPermission(sDump, pid, uid)) {
2673 result.appendFormat("Permission Denial: "
2674 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2675 } else {
2676 // Try to get the main lock, but give up after one second
2677 // (this would indicate SF is stuck, but we want to be able to
2678 // print something in dumpsys).
2679 status_t err = mStateLock.timedLock(s2ns(1));
2680 bool locked = (err == NO_ERROR);
2681 if (!locked) {
2682 result.appendFormat(
2683 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2684 "dumping anyways (no locks held)\n", strerror(-err), err);
2685 }
2686
2687 bool dumpAll = true;
2688 size_t index = 0;
2689 size_t numArgs = args.size();
2690 if (numArgs) {
2691 if ((index < numArgs) &&
2692 (args[index] == String16("--list"))) {
2693 index++;
2694 listLayersLocked(args, index, result);
2695 dumpAll = false;
2696 }
2697
2698 if ((index < numArgs) &&
2699 (args[index] == String16("--latency"))) {
2700 index++;
2701 dumpStatsLocked(args, index, result);
2702 dumpAll = false;
2703 }
2704
2705 if ((index < numArgs) &&
2706 (args[index] == String16("--latency-clear"))) {
2707 index++;
2708 clearStatsLocked(args, index, result);
2709 dumpAll = false;
2710 }
2711
2712 if ((index < numArgs) &&
2713 (args[index] == String16("--dispsync"))) {
2714 index++;
2715 mPrimaryDispSync.dump(result);
2716 dumpAll = false;
2717 }
2718
2719 if ((index < numArgs) &&
2720 (args[index] == String16("--static-screen"))) {
2721 index++;
2722 dumpStaticScreenStats(result);
2723 dumpAll = false;
2724 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08002725
2726 if ((index < numArgs) &&
2727 (args[index] == String16("--fences"))) {
2728 index++;
2729 mFenceTracker.dump(&result);
2730 dumpAll = false;
2731 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002732 }
2733
2734 if (dumpAll) {
2735 dumpAllLocked(args, index, result);
2736 }
2737
2738 if (locked) {
2739 mStateLock.unlock();
2740 }
2741 }
2742 write(fd, result.string(), result.size());
2743 return NO_ERROR;
2744}
2745
2746void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2747 size_t& /* index */, String8& result) const
2748{
2749 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2750 const size_t count = currentLayers.size();
2751 for (size_t i=0 ; i<count ; i++) {
2752 const sp<Layer>& layer(currentLayers[i]);
2753 result.appendFormat("%s\n", layer->getName().string());
2754 }
2755}
2756
2757void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2758 String8& result) const
2759{
2760 String8 name;
2761 if (index < args.size()) {
2762 name = String8(args[index]);
2763 index++;
2764 }
2765
2766 const nsecs_t period =
2767 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2768 result.appendFormat("%" PRId64 "\n", period);
2769
2770 if (name.isEmpty()) {
2771 mAnimFrameTracker.dumpStats(result);
2772 } else {
2773 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2774 const size_t count = currentLayers.size();
2775 for (size_t i=0 ; i<count ; i++) {
2776 const sp<Layer>& layer(currentLayers[i]);
2777 if (name == layer->getName()) {
2778 layer->dumpFrameStats(result);
2779 }
2780 }
2781 }
2782}
2783
2784void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2785 String8& /* result */)
2786{
2787 String8 name;
2788 if (index < args.size()) {
2789 name = String8(args[index]);
2790 index++;
2791 }
2792
2793 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2794 const size_t count = currentLayers.size();
2795 for (size_t i=0 ; i<count ; i++) {
2796 const sp<Layer>& layer(currentLayers[i]);
2797 if (name.isEmpty() || (name == layer->getName())) {
2798 layer->clearFrameStats();
2799 }
2800 }
2801
2802 mAnimFrameTracker.clearStats();
2803}
2804
2805// This should only be called from the main thread. Otherwise it would need
2806// the lock and should use mCurrentState rather than mDrawingState.
2807void SurfaceFlinger::logFrameStats() {
2808 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2809 const size_t count = drawingLayers.size();
2810 for (size_t i=0 ; i<count ; i++) {
2811 const sp<Layer>& layer(drawingLayers[i]);
2812 layer->logFrameStats();
2813 }
2814
2815 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2816}
2817
2818/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2819{
2820 static const char* config =
2821 " [sf"
2822#ifdef HAS_CONTEXT_PRIORITY
2823 " HAS_CONTEXT_PRIORITY"
2824#endif
2825#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2826 " NEVER_DEFAULT_TO_ASYNC_MODE"
2827#endif
2828#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2829 " TARGET_DISABLE_TRIPLE_BUFFERING"
2830#endif
2831 "]";
2832 result.append(config);
2833}
2834
2835void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2836{
2837 result.appendFormat("Static screen stats:\n");
2838 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2839 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2840 float percent = 100.0f *
2841 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2842 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2843 b + 1, bucketTimeSec, percent);
2844 }
2845 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2846 float percent = 100.0f *
2847 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2848 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2849 NUM_BUCKETS - 1, bucketTimeSec, percent);
2850}
2851
Dan Stozae77c7662016-05-13 11:37:28 -07002852void SurfaceFlinger::recordBufferingStats(const char* layerName,
2853 std::vector<OccupancyTracker::Segment>&& history) {
2854 Mutex::Autolock lock(mBufferingStatsMutex);
2855 auto& stats = mBufferingStats[layerName];
2856 for (const auto& segment : history) {
2857 if (!segment.usedThirdBuffer) {
2858 stats.twoBufferTime += segment.totalTime;
2859 }
2860 if (segment.occupancyAverage < 1.0f) {
2861 stats.doubleBufferedTime += segment.totalTime;
2862 } else if (segment.occupancyAverage < 2.0f) {
2863 stats.tripleBufferedTime += segment.totalTime;
2864 }
2865 ++stats.numSegments;
2866 stats.totalTime += segment.totalTime;
2867 }
2868}
2869
2870void SurfaceFlinger::dumpBufferingStats(String8& result) const {
2871 result.append("Buffering stats:\n");
2872 result.append(" [Layer name] <Active time> <Two buffer> "
2873 "<Double buffered> <Triple buffered>\n");
2874 Mutex::Autolock lock(mBufferingStatsMutex);
2875 typedef std::tuple<std::string, float, float, float> BufferTuple;
2876 std::map<float, BufferTuple, std::greater<float>> sorted;
2877 for (const auto& statsPair : mBufferingStats) {
2878 const char* name = statsPair.first.c_str();
2879 const BufferingStats& stats = statsPair.second;
2880 if (stats.numSegments == 0) {
2881 continue;
2882 }
2883 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
2884 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
2885 stats.totalTime;
2886 float doubleBufferRatio = static_cast<float>(
2887 stats.doubleBufferedTime) / stats.totalTime;
2888 float tripleBufferRatio = static_cast<float>(
2889 stats.tripleBufferedTime) / stats.totalTime;
2890 sorted.insert({activeTime, {name, twoBufferRatio,
2891 doubleBufferRatio, tripleBufferRatio}});
2892 }
2893 for (const auto& sortedPair : sorted) {
2894 float activeTime = sortedPair.first;
2895 const BufferTuple& values = sortedPair.second;
2896 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
2897 std::get<0>(values).c_str(), activeTime,
2898 std::get<1>(values), std::get<2>(values),
2899 std::get<3>(values));
2900 }
2901 result.append("\n");
2902}
2903
Dan Stoza9e56aa02015-11-02 13:00:03 -08002904void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2905 String8& result) const
2906{
2907 bool colorize = false;
2908 if (index < args.size()
2909 && (args[index] == String16("--color"))) {
2910 colorize = true;
2911 index++;
2912 }
2913
2914 Colorizer colorizer(colorize);
2915
2916 // figure out if we're stuck somewhere
2917 const nsecs_t now = systemTime();
2918 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2919 const nsecs_t inTransaction(mDebugInTransaction);
2920 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2921 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2922
2923 /*
2924 * Dump library configuration.
2925 */
2926
2927 colorizer.bold(result);
2928 result.append("Build configuration:");
2929 colorizer.reset(result);
2930 appendSfConfigString(result);
2931 appendUiConfigString(result);
2932 appendGuiConfigString(result);
2933 result.append("\n");
2934
2935 colorizer.bold(result);
2936 result.append("Sync configuration: ");
2937 colorizer.reset(result);
2938 result.append(SyncFeatures::getInstance().toString());
2939 result.append("\n");
2940
2941 colorizer.bold(result);
2942 result.append("DispSync configuration: ");
2943 colorizer.reset(result);
2944 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2945 "present offset %d ns (refresh %" PRId64 " ns)",
2946 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2947 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2948 result.append("\n");
2949
2950 // Dump static screen stats
2951 result.append("\n");
2952 dumpStaticScreenStats(result);
2953 result.append("\n");
2954
Dan Stozae77c7662016-05-13 11:37:28 -07002955 dumpBufferingStats(result);
2956
Dan Stoza9e56aa02015-11-02 13:00:03 -08002957 /*
2958 * Dump the visible layer list
2959 */
2960 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2961 const size_t count = currentLayers.size();
2962 colorizer.bold(result);
2963 result.appendFormat("Visible layers (count = %zu)\n", count);
2964 colorizer.reset(result);
2965 for (size_t i=0 ; i<count ; i++) {
2966 const sp<Layer>& layer(currentLayers[i]);
2967 layer->dump(result, colorizer);
2968 }
2969
2970 /*
2971 * Dump Display state
2972 */
2973
2974 colorizer.bold(result);
2975 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2976 colorizer.reset(result);
2977 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2978 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2979 hw->dump(result);
2980 }
2981
2982 /*
2983 * Dump SurfaceFlinger global state
2984 */
2985
2986 colorizer.bold(result);
2987 result.append("SurfaceFlinger global state:\n");
2988 colorizer.reset(result);
2989
2990 HWComposer& hwc(getHwComposer());
2991 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2992
2993 colorizer.bold(result);
2994 result.appendFormat("EGL implementation : %s\n",
2995 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2996 colorizer.reset(result);
2997 result.appendFormat("%s\n",
2998 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2999
3000 mRenderEngine->dump(result);
3001
3002 hw->undefinedRegion.dump(result, "undefinedRegion");
3003 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
3004 hw->getOrientation(), hw->isDisplayOn());
3005 result.appendFormat(
3006 " last eglSwapBuffers() time: %f us\n"
3007 " last transaction time : %f us\n"
3008 " transaction-flags : %08x\n"
3009 " refresh-rate : %f fps\n"
3010 " x-dpi : %f\n"
3011 " y-dpi : %f\n"
3012 " gpu_to_cpu_unsupported : %d\n"
3013 ,
3014 mLastSwapBufferTime/1000.0,
3015 mLastTransactionTime/1000.0,
3016 mTransactionFlags,
3017 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
3018 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
3019 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
3020 !mGpuToCpuSupported);
3021
3022 result.appendFormat(" eglSwapBuffers time: %f us\n",
3023 inSwapBuffersDuration/1000.0);
3024
3025 result.appendFormat(" transaction time: %f us\n",
3026 inTransactionDuration/1000.0);
3027
3028 /*
3029 * VSYNC state
3030 */
3031 mEventThread->dump(result);
3032
3033 /*
3034 * Dump HWComposer state
3035 */
3036 colorizer.bold(result);
3037 result.append("h/w composer state:\n");
3038 colorizer.reset(result);
3039 result.appendFormat(" h/w composer %s and %s\n",
3040 hwc.initCheck()==NO_ERROR ? "present" : "not present",
3041 (mDebugDisableHWC || mDebugRegion || mDaltonize
3042 || mHasColorMatrix) ? "disabled" : "enabled");
3043 hwc.dump(result);
3044
3045 /*
3046 * Dump gralloc state
3047 */
3048 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
3049 alloc.dump(result);
3050}
3051
3052const Vector< sp<Layer> >&
3053SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
3054 // Note: mStateLock is held here
3055 wp<IBinder> dpy;
3056 for (size_t i=0 ; i<mDisplays.size() ; i++) {
3057 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
3058 dpy = mDisplays.keyAt(i);
3059 break;
3060 }
3061 }
3062 if (dpy == NULL) {
3063 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
3064 // Just use the primary display so we have something to return
3065 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
3066 }
3067 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
3068}
3069
3070bool SurfaceFlinger::startDdmConnection()
3071{
3072 void* libddmconnection_dso =
3073 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
3074 if (!libddmconnection_dso) {
3075 return false;
3076 }
3077 void (*DdmConnection_start)(const char* name);
3078 DdmConnection_start =
3079 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
3080 if (!DdmConnection_start) {
3081 dlclose(libddmconnection_dso);
3082 return false;
3083 }
3084 (*DdmConnection_start)(getServiceName());
3085 return true;
3086}
3087
3088status_t SurfaceFlinger::onTransact(
3089 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3090{
3091 switch (code) {
3092 case CREATE_CONNECTION:
3093 case CREATE_DISPLAY:
3094 case SET_TRANSACTION_STATE:
3095 case BOOT_FINISHED:
3096 case CLEAR_ANIMATION_FRAME_STATS:
3097 case GET_ANIMATION_FRAME_STATS:
3098 case SET_POWER_MODE:
Dan Stozac4f471e2016-03-24 09:31:08 -07003099 case GET_HDR_CAPABILITIES:
Dan Stoza9e56aa02015-11-02 13:00:03 -08003100 {
3101 // codes that require permission check
3102 IPCThreadState* ipc = IPCThreadState::self();
3103 const int pid = ipc->getCallingPid();
3104 const int uid = ipc->getCallingUid();
3105 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3106 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3107 ALOGE("Permission Denial: "
3108 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3109 return PERMISSION_DENIED;
3110 }
3111 break;
3112 }
3113 case CAPTURE_SCREEN:
3114 {
3115 // codes that require permission check
3116 IPCThreadState* ipc = IPCThreadState::self();
3117 const int pid = ipc->getCallingPid();
3118 const int uid = ipc->getCallingUid();
3119 if ((uid != AID_GRAPHICS) &&
3120 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3121 ALOGE("Permission Denial: "
3122 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3123 return PERMISSION_DENIED;
3124 }
3125 break;
3126 }
3127 }
3128
3129 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3130 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3131 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3132 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3133 IPCThreadState* ipc = IPCThreadState::self();
3134 const int pid = ipc->getCallingPid();
3135 const int uid = ipc->getCallingUid();
3136 ALOGE("Permission Denial: "
3137 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3138 return PERMISSION_DENIED;
3139 }
3140 int n;
3141 switch (code) {
3142 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3143 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3144 return NO_ERROR;
3145 case 1002: // SHOW_UPDATES
3146 n = data.readInt32();
3147 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3148 invalidateHwcGeometry();
3149 repaintEverything();
3150 return NO_ERROR;
3151 case 1004:{ // repaint everything
3152 repaintEverything();
3153 return NO_ERROR;
3154 }
3155 case 1005:{ // force transaction
3156 setTransactionFlags(
3157 eTransactionNeeded|
3158 eDisplayTransactionNeeded|
3159 eTraversalNeeded);
3160 return NO_ERROR;
3161 }
3162 case 1006:{ // send empty update
3163 signalRefresh();
3164 return NO_ERROR;
3165 }
3166 case 1008: // toggle use of hw composer
3167 n = data.readInt32();
3168 mDebugDisableHWC = n ? 1 : 0;
3169 invalidateHwcGeometry();
3170 repaintEverything();
3171 return NO_ERROR;
3172 case 1009: // toggle use of transform hint
3173 n = data.readInt32();
3174 mDebugDisableTransformHint = n ? 1 : 0;
3175 invalidateHwcGeometry();
3176 repaintEverything();
3177 return NO_ERROR;
3178 case 1010: // interrogate.
3179 reply->writeInt32(0);
3180 reply->writeInt32(0);
3181 reply->writeInt32(mDebugRegion);
3182 reply->writeInt32(0);
3183 reply->writeInt32(mDebugDisableHWC);
3184 return NO_ERROR;
3185 case 1013: {
3186 Mutex::Autolock _l(mStateLock);
3187 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3188 reply->writeInt32(hw->getPageFlipCount());
3189 return NO_ERROR;
3190 }
3191 case 1014: {
3192 // daltonize
3193 n = data.readInt32();
3194 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003195 case 1:
3196 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
3197 break;
3198 case 2:
3199 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
3200 break;
3201 case 3:
3202 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
3203 break;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003204 }
3205 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003206 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003207 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003208 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Dan Stoza9e56aa02015-11-02 13:00:03 -08003209 }
3210 mDaltonize = n > 0;
3211 invalidateHwcGeometry();
3212 repaintEverything();
3213 return NO_ERROR;
3214 }
3215 case 1015: {
3216 // apply a color matrix
3217 n = data.readInt32();
3218 mHasColorMatrix = n ? 1 : 0;
3219 if (n) {
3220 // color matrix is sent as mat3 matrix followed by vec3
3221 // offset, then packed into a mat4 where the last row is
3222 // the offset and extra values are 0
3223 for (size_t i = 0 ; i < 4; i++) {
3224 for (size_t j = 0; j < 4; j++) {
3225 mColorMatrix[i][j] = data.readFloat();
3226 }
3227 }
3228 } else {
3229 mColorMatrix = mat4();
3230 }
3231 invalidateHwcGeometry();
3232 repaintEverything();
3233 return NO_ERROR;
3234 }
3235 // This is an experimental interface
3236 // Needs to be shifted to proper binder interface when we productize
3237 case 1016: {
3238 n = data.readInt32();
3239 mPrimaryDispSync.setRefreshSkipCount(n);
3240 return NO_ERROR;
3241 }
3242 case 1017: {
3243 n = data.readInt32();
3244 mForceFullDamage = static_cast<bool>(n);
3245 return NO_ERROR;
3246 }
3247 case 1018: { // Modify Choreographer's phase offset
3248 n = data.readInt32();
3249 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3250 return NO_ERROR;
3251 }
3252 case 1019: { // Modify SurfaceFlinger's phase offset
3253 n = data.readInt32();
3254 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3255 return NO_ERROR;
3256 }
Irvel468051e2016-06-13 16:44:44 -07003257 case 1020: { // Layer updates interceptor
3258 n = data.readInt32();
3259 if (n) {
3260 ALOGV("Interceptor enabled");
3261 mInterceptor.enable(mDrawingState.layersSortedByZ);
3262 }
3263 else{
3264 ALOGV("Interceptor disabled");
3265 mInterceptor.disable();
3266 }
3267 return NO_ERROR;
3268 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003269 }
3270 }
3271 return err;
3272}
3273
3274void SurfaceFlinger::repaintEverything() {
3275 android_atomic_or(1, &mRepaintEverything);
3276 signalTransaction();
3277}
3278
3279// ---------------------------------------------------------------------------
3280// Capture screen into an IGraphiBufferProducer
3281// ---------------------------------------------------------------------------
3282
3283/* The code below is here to handle b/8734824
3284 *
3285 * We create a IGraphicBufferProducer wrapper that forwards all calls
3286 * from the surfaceflinger thread to the calling binder thread, where they
3287 * are executed. This allows the calling thread in the calling process to be
3288 * reused and not depend on having "enough" binder threads to handle the
3289 * requests.
3290 */
3291class GraphicProducerWrapper : public BBinder, public MessageHandler {
3292 /* Parts of GraphicProducerWrapper are run on two different threads,
3293 * communicating by sending messages via Looper but also by shared member
3294 * data. Coherence maintenance is subtle and in places implicit (ugh).
3295 *
3296 * Don't rely on Looper's sendMessage/handleMessage providing
3297 * release/acquire semantics for any data not actually in the Message.
3298 * Data going from surfaceflinger to binder threads needs to be
3299 * synchronized explicitly.
3300 *
3301 * Barrier open/wait do provide release/acquire semantics. This provides
3302 * implicit synchronization for data coming back from binder to
3303 * surfaceflinger threads.
3304 */
3305
3306 sp<IGraphicBufferProducer> impl;
3307 sp<Looper> looper;
3308 status_t result;
3309 bool exitPending;
3310 bool exitRequested;
3311 Barrier barrier;
3312 uint32_t code;
3313 Parcel const* data;
3314 Parcel* reply;
3315
3316 enum {
3317 MSG_API_CALL,
3318 MSG_EXIT
3319 };
3320
3321 /*
3322 * Called on surfaceflinger thread. This is called by our "fake"
3323 * BpGraphicBufferProducer. We package the data and reply Parcel and
3324 * forward them to the binder thread.
3325 */
3326 virtual status_t transact(uint32_t code,
3327 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3328 this->code = code;
3329 this->data = &data;
3330 this->reply = reply;
3331 if (exitPending) {
3332 // if we've exited, we run the message synchronously right here.
3333 // note (JH): as far as I can tell from looking at the code, this
3334 // never actually happens. if it does, i'm not sure if it happens
3335 // on the surfaceflinger or binder thread.
3336 handleMessage(Message(MSG_API_CALL));
3337 } else {
3338 barrier.close();
3339 // Prevent stores to this->{code, data, reply} from being
3340 // reordered later than the construction of Message.
3341 atomic_thread_fence(memory_order_release);
3342 looper->sendMessage(this, Message(MSG_API_CALL));
3343 barrier.wait();
3344 }
3345 return result;
3346 }
3347
3348 /*
3349 * here we run on the binder thread. All we've got to do is
3350 * call the real BpGraphicBufferProducer.
3351 */
3352 virtual void handleMessage(const Message& message) {
3353 int what = message.what;
3354 // Prevent reads below from happening before the read from Message
3355 atomic_thread_fence(memory_order_acquire);
3356 if (what == MSG_API_CALL) {
3357 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3358 barrier.open();
3359 } else if (what == MSG_EXIT) {
3360 exitRequested = true;
3361 }
3362 }
3363
3364public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -07003365 explicit GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
Dan Stoza9e56aa02015-11-02 13:00:03 -08003366 : impl(impl),
3367 looper(new Looper(true)),
3368 result(NO_ERROR),
3369 exitPending(false),
3370 exitRequested(false),
3371 code(0),
3372 data(NULL),
3373 reply(NULL)
3374 {}
3375
3376 // Binder thread
3377 status_t waitForResponse() {
3378 do {
3379 looper->pollOnce(-1);
3380 } while (!exitRequested);
3381 return result;
3382 }
3383
3384 // Client thread
3385 void exit(status_t result) {
3386 this->result = result;
3387 exitPending = true;
3388 // Ensure this->result is visible to the binder thread before it
3389 // handles the message.
3390 atomic_thread_fence(memory_order_release);
3391 looper->sendMessage(this, Message(MSG_EXIT));
3392 }
3393};
3394
3395
3396status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3397 const sp<IGraphicBufferProducer>& producer,
3398 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3399 uint32_t minLayerZ, uint32_t maxLayerZ,
3400 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3401
3402 if (CC_UNLIKELY(display == 0))
3403 return BAD_VALUE;
3404
3405 if (CC_UNLIKELY(producer == 0))
3406 return BAD_VALUE;
3407
3408 // if we have secure windows on this display, never allow the screen capture
3409 // unless the producer interface is local (i.e.: we can take a screenshot for
3410 // ourselves).
3411 bool isLocalScreenshot = IInterface::asBinder(producer)->localBinder();
3412
3413 // Convert to surfaceflinger's internal rotation type.
3414 Transform::orientation_flags rotationFlags;
3415 switch (rotation) {
3416 case ISurfaceComposer::eRotateNone:
3417 rotationFlags = Transform::ROT_0;
3418 break;
3419 case ISurfaceComposer::eRotate90:
3420 rotationFlags = Transform::ROT_90;
3421 break;
3422 case ISurfaceComposer::eRotate180:
3423 rotationFlags = Transform::ROT_180;
3424 break;
3425 case ISurfaceComposer::eRotate270:
3426 rotationFlags = Transform::ROT_270;
3427 break;
3428 default:
3429 rotationFlags = Transform::ROT_0;
3430 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3431 break;
3432 }
3433
3434 class MessageCaptureScreen : public MessageBase {
3435 SurfaceFlinger* flinger;
3436 sp<IBinder> display;
3437 sp<IGraphicBufferProducer> producer;
3438 Rect sourceCrop;
3439 uint32_t reqWidth, reqHeight;
3440 uint32_t minLayerZ,maxLayerZ;
3441 bool useIdentityTransform;
3442 Transform::orientation_flags rotation;
3443 status_t result;
3444 bool isLocalScreenshot;
3445 public:
3446 MessageCaptureScreen(SurfaceFlinger* flinger,
3447 const sp<IBinder>& display,
3448 const sp<IGraphicBufferProducer>& producer,
3449 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3450 uint32_t minLayerZ, uint32_t maxLayerZ,
3451 bool useIdentityTransform,
3452 Transform::orientation_flags rotation,
3453 bool isLocalScreenshot)
3454 : flinger(flinger), display(display), producer(producer),
3455 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3456 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3457 useIdentityTransform(useIdentityTransform),
3458 rotation(rotation), result(PERMISSION_DENIED),
3459 isLocalScreenshot(isLocalScreenshot)
3460 {
3461 }
3462 status_t getResult() const {
3463 return result;
3464 }
3465 virtual bool handler() {
3466 Mutex::Autolock _l(flinger->mStateLock);
3467 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3468 result = flinger->captureScreenImplLocked(hw, producer,
3469 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3470 useIdentityTransform, rotation, isLocalScreenshot);
3471 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3472 return true;
3473 }
3474 };
3475
Dan Stoza9e56aa02015-11-02 13:00:03 -08003476 // this creates a "fake" BBinder which will serve as a "fake" remote
3477 // binder to receive the marshaled calls and forward them to the
3478 // real remote (a BpGraphicBufferProducer)
3479 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3480
3481 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3482 // which does the marshaling work forwards to our "fake remote" above.
3483 sp<MessageBase> msg = new MessageCaptureScreen(this,
3484 display, IGraphicBufferProducer::asInterface( wrapper ),
3485 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3486 useIdentityTransform, rotationFlags, isLocalScreenshot);
3487
3488 status_t res = postMessageAsync(msg);
3489 if (res == NO_ERROR) {
3490 res = wrapper->waitForResponse();
3491 }
3492 return res;
3493}
3494
3495
3496void SurfaceFlinger::renderScreenImplLocked(
3497 const sp<const DisplayDevice>& hw,
3498 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3499 uint32_t minLayerZ, uint32_t maxLayerZ,
3500 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3501{
3502 ATRACE_CALL();
3503 RenderEngine& engine(getRenderEngine());
3504
3505 // get screen geometry
3506 const int32_t hw_w = hw->getWidth();
3507 const int32_t hw_h = hw->getHeight();
3508 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3509 static_cast<int32_t>(reqHeight) != hw_h;
3510
3511 // if a default or invalid sourceCrop is passed in, set reasonable values
3512 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3513 !sourceCrop.isValid()) {
3514 sourceCrop.setLeftTop(Point(0, 0));
3515 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3516 }
3517
3518 // ensure that sourceCrop is inside screen
3519 if (sourceCrop.left < 0) {
3520 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3521 }
3522 if (sourceCrop.right > hw_w) {
3523 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3524 }
3525 if (sourceCrop.top < 0) {
3526 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3527 }
3528 if (sourceCrop.bottom > hw_h) {
3529 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3530 }
3531
3532 // make sure to clear all GL error flags
3533 engine.checkErrors();
3534
3535 // set-up our viewport
3536 engine.setViewportAndProjection(
3537 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3538 engine.disableTexturing();
3539
3540 // redraw the screen entirely...
3541 engine.clearWithColor(0, 0, 0, 1);
3542
3543 const LayerVector& layers( mDrawingState.layersSortedByZ );
3544 const size_t count = layers.size();
3545 for (size_t i=0 ; i<count ; ++i) {
3546 const sp<Layer>& layer(layers[i]);
3547 const Layer::State& state(layer->getDrawingState());
3548 if (state.layerStack == hw->getLayerStack()) {
3549 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3550 if (layer->isVisible()) {
3551 if (filtering) layer->setFiltering(true);
3552 layer->draw(hw, useIdentityTransform);
3553 if (filtering) layer->setFiltering(false);
3554 }
3555 }
3556 }
3557 }
3558
3559 // compositionComplete is needed for older driver
3560 hw->compositionComplete();
3561 hw->setViewportAndProjection();
3562}
3563
3564
3565status_t SurfaceFlinger::captureScreenImplLocked(
3566 const sp<const DisplayDevice>& hw,
3567 const sp<IGraphicBufferProducer>& producer,
3568 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3569 uint32_t minLayerZ, uint32_t maxLayerZ,
3570 bool useIdentityTransform, Transform::orientation_flags rotation,
3571 bool isLocalScreenshot)
3572{
3573 ATRACE_CALL();
3574
3575 // get screen geometry
3576 uint32_t hw_w = hw->getWidth();
3577 uint32_t hw_h = hw->getHeight();
3578
3579 if (rotation & Transform::ROT_90) {
3580 std::swap(hw_w, hw_h);
3581 }
3582
3583 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3584 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3585 reqWidth, reqHeight, hw_w, hw_h);
3586 return BAD_VALUE;
3587 }
3588
3589 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3590 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3591
3592 bool secureLayerIsVisible = false;
3593 const LayerVector& layers(mDrawingState.layersSortedByZ);
3594 const size_t count = layers.size();
3595 for (size_t i = 0 ; i < count ; ++i) {
3596 const sp<Layer>& layer(layers[i]);
3597 const Layer::State& state(layer->getDrawingState());
3598 if (state.layerStack == hw->getLayerStack() && state.z >= minLayerZ &&
3599 state.z <= maxLayerZ && layer->isVisible() &&
3600 layer->isSecure()) {
3601 secureLayerIsVisible = true;
3602 }
3603 }
3604
3605 if (!isLocalScreenshot && secureLayerIsVisible) {
3606 ALOGW("FB is protected: PERMISSION_DENIED");
3607 return PERMISSION_DENIED;
3608 }
3609
3610 // create a surface (because we're a producer, and we need to
3611 // dequeue/queue a buffer)
3612 sp<Surface> sur = new Surface(producer, false);
3613 ANativeWindow* window = sur.get();
3614
3615 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3616 if (result == NO_ERROR) {
3617 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3618 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3619
3620 int err = 0;
3621 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3622 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3623 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3624 err |= native_window_set_usage(window, usage);
3625
3626 if (err == NO_ERROR) {
3627 ANativeWindowBuffer* buffer;
3628 /* TODO: Once we have the sync framework everywhere this can use
3629 * server-side waits on the fence that dequeueBuffer returns.
3630 */
3631 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3632 if (result == NO_ERROR) {
3633 int syncFd = -1;
3634 // create an EGLImage from the buffer so we can later
3635 // turn it into a texture
3636 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3637 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3638 if (image != EGL_NO_IMAGE_KHR) {
3639 // this binds the given EGLImage as a framebuffer for the
3640 // duration of this scope.
3641 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3642 if (imageBond.getStatus() == NO_ERROR) {
3643 // this will in fact render into our dequeued buffer
3644 // via an FBO, which means we didn't have to create
3645 // an EGLSurface and therefore we're not
3646 // dependent on the context's EGLConfig.
3647 renderScreenImplLocked(
3648 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3649 useIdentityTransform, rotation);
3650
3651 // Attempt to create a sync khr object that can produce a sync point. If that
3652 // isn't available, create a non-dupable sync object in the fallback path and
3653 // wait on it directly.
3654 EGLSyncKHR sync;
3655 if (!DEBUG_SCREENSHOTS) {
3656 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3657 // native fence fd will not be populated until flush() is done.
3658 getRenderEngine().flush();
3659 } else {
3660 sync = EGL_NO_SYNC_KHR;
3661 }
3662 if (sync != EGL_NO_SYNC_KHR) {
3663 // get the sync fd
3664 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3665 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3666 ALOGW("captureScreen: failed to dup sync khr object");
3667 syncFd = -1;
3668 }
3669 eglDestroySyncKHR(mEGLDisplay, sync);
3670 } else {
3671 // fallback path
3672 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3673 if (sync != EGL_NO_SYNC_KHR) {
3674 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3675 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3676 EGLint eglErr = eglGetError();
3677 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3678 ALOGW("captureScreen: fence wait timed out");
3679 } else {
3680 ALOGW_IF(eglErr != EGL_SUCCESS,
3681 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3682 }
3683 eglDestroySyncKHR(mEGLDisplay, sync);
3684 } else {
3685 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3686 }
3687 }
3688 if (DEBUG_SCREENSHOTS) {
3689 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3690 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3691 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3692 hw, minLayerZ, maxLayerZ);
3693 delete [] pixels;
3694 }
3695
3696 } else {
3697 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3698 result = INVALID_OPERATION;
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003699 window->cancelBuffer(window, buffer, syncFd);
3700 buffer = NULL;
Dan Stoza9e56aa02015-11-02 13:00:03 -08003701 }
3702 // destroy our image
3703 eglDestroyImageKHR(mEGLDisplay, image);
3704 } else {
3705 result = BAD_VALUE;
3706 }
Prathmesh Prabhuf3209b02016-03-09 16:54:45 -08003707 if (buffer) {
3708 // queueBuffer takes ownership of syncFd
3709 result = window->queueBuffer(window, buffer, syncFd);
3710 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08003711 }
3712 } else {
3713 result = BAD_VALUE;
3714 }
3715 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3716 }
3717
3718 return result;
3719}
3720
Pablo Ceballosce796e72016-02-04 19:10:51 -08003721bool SurfaceFlinger::getFrameTimestamps(const Layer& layer,
3722 uint64_t frameNumber, FrameTimestamps* outTimestamps) {
3723 return mFenceTracker.getFrameTimestamps(layer, frameNumber, outTimestamps);
3724}
3725
Dan Stoza9e56aa02015-11-02 13:00:03 -08003726void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3727 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3728 if (DEBUG_SCREENSHOTS) {
3729 for (size_t y=0 ; y<h ; y++) {
3730 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3731 for (size_t x=0 ; x<w ; x++) {
3732 if (p[x] != 0xFF000000) return;
3733 }
3734 }
3735 ALOGE("*** we just took a black screenshot ***\n"
3736 "requested minz=%d, maxz=%d, layerStack=%d",
3737 minLayerZ, maxLayerZ, hw->getLayerStack());
3738 const LayerVector& layers( mDrawingState.layersSortedByZ );
3739 const size_t count = layers.size();
3740 for (size_t i=0 ; i<count ; ++i) {
3741 const sp<Layer>& layer(layers[i]);
3742 const Layer::State& state(layer->getDrawingState());
3743 const bool visible = (state.layerStack == hw->getLayerStack())
3744 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3745 && (layer->isVisible());
3746 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3747 visible ? '+' : '-',
3748 i, layer->getName().string(), state.layerStack, state.z,
3749 layer->isVisible(), state.flags, state.alpha);
3750 }
3751 }
3752}
3753
3754// ---------------------------------------------------------------------------
3755
3756SurfaceFlinger::LayerVector::LayerVector() {
3757}
3758
3759SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3760 : SortedVector<sp<Layer> >(rhs) {
3761}
3762
3763int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3764 const void* rhs) const
3765{
3766 // sort layers per layer-stack, then by z-order and finally by sequence
3767 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3768 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3769
3770 uint32_t ls = l->getCurrentState().layerStack;
3771 uint32_t rs = r->getCurrentState().layerStack;
3772 if (ls != rs)
3773 return ls - rs;
3774
3775 uint32_t lz = l->getCurrentState().z;
3776 uint32_t rz = r->getCurrentState().z;
3777 if (lz != rz)
3778 return lz - rz;
3779
3780 return l->sequence - r->sequence;
3781}
3782
3783// ---------------------------------------------------------------------------
3784
3785SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3786 : type(DisplayDevice::DISPLAY_ID_INVALID),
3787 layerStack(DisplayDevice::NO_LAYER_STACK),
3788 orientation(0),
3789 width(0),
3790 height(0),
3791 isSecure(false) {
3792}
3793
3794SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(
3795 DisplayDevice::DisplayType type, bool isSecure)
3796 : type(type),
3797 layerStack(DisplayDevice::NO_LAYER_STACK),
3798 orientation(0),
3799 width(0),
3800 height(0),
3801 isSecure(isSecure) {
3802 viewport.makeInvalid();
3803 frame.makeInvalid();
3804}
3805
3806// ---------------------------------------------------------------------------
3807
3808}; // namespace android
3809
3810
3811#if defined(__gl_h_)
3812#error "don't include gl/gl.h in this file"
3813#endif
3814
3815#if defined(__gl2_h_)
3816#error "don't include gl2/gl2.h in this file"
3817#endif