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