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