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